5.编程方法 为了编译pthreads,你必须包含pthreads头文件,#include并且链接到pthread库。例如,cc hello_world.c -o hello_world -lpthreads(在alpha上,你还应包含 -lc_r)。为了使用信号量库,你也应包含它的头文件并且链接到目标文件或者库。DEC pthreads是建立在POSIX IV 线程标准的基础上的,而不是在POSIX VIII线程基础上的。pthread_join函数允许一个线程去等待另一个线程的结束。这个函数可以被用在Hello World程序中来替代semaphore_up()/semaphore_down()的信号量操作,DEC对pthread_join函数的实现当指定的线程目标不再存在时将变得不可靠。例如,在下面的代码中,如果some_thread不再存在,pthread_join不会返回而是会导致错误。 pthread_t some_thread; void *exit_status; pthread_join( some_thread, &exit_status ); 另一些奇怪的错误会在这个线程的函数外发生。当这些错误很说发生并且离的较远,一些库做了"单进程"的假设。例如,我们已经历过了在使用有缓存的输入输出流函数fread和fwrite发生的间歇性的困难,这只能归因于竞争情形。在错误的问题上,虽然我们不检查线程相关函数的返回值,返回值必须始终被检查。几乎所有的pthreads相关的函数如果返回-1这代表有错误。比如: pthread_t some_thread; if ( pthread_create( &some_thread, ... ) == -1 ) { perror("Thread creation error"); exit(1); } 信号量库会打印出信息并且在有错误的情况下退出。一些有用的函数没有在例子中提到: pthread_yield(); Informs the scheduler that the thread is willing to yield its quantum, requires no arguments. pthread_t me; me = pthread_self(); Allows a pthread to obtain its own identifier pthread_t thread; pthread_detach(thread); Informs the library that the threads exit status will not be needed by subsequent pthread_join calls resulting in better threads performance. 
|