软件工程

本类阅读TOP10

·PHP4 + MYSQL + APACHE 在 WIN 系统下的安装、配置
·Linux 入门常用命令(1)
·Linux 入门常用命令(2)
·使用 DCPROMO/FORCEREMOVAL 命令强制将 Active Directory 域控制器降级
·DirectShow学习(八): CBaseRender类及相应Pin类的源代码分析
·基于ICE方式SIP信令穿透Symmetric NAT技术研究
·Windows 2003网络负载均衡的实现
·一网打尽Win十四种系统故障解决方法
·数百种 Windows 软件的免费替代品列表
·收藏---行百里半九十

分类导航
VC语言Delphi
VB语言ASP
PerlJava
Script数据库
其他语言游戏开发
文件格式网站制作
软件工程.NET开发
开始使用pthreads(5)编程方法

作者:未知 来源:月光软件站 加入时间:2005-5-13 月光软件站

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.




相关文章

相关软件