跨平台多线程库pthread

来源:互联网 发布:淘宝钻石店出售 编辑:程序博客网 时间:2024/06/08 06:39

【原创文章,转载请保留或注明出处:http://blog.csdn.net/yinyhy/article/details/10959997】

1.简介

POSⅨ thread 简称为pthread,Posix线程是一个POSⅨ标准线程,该标准定义内部API创建和操纵线程。

线程库实行了POSIX线程标准通常称为pthreads.POSIX线程具有很好的可移植的性,使用pthread编写的代码可运行于Solaris、FreeBSD、Linux 等平台,Windows平台亦有pthread-win32可供使用。

Pthreads定义了一套 C程序语言类型、函数与常量,它以 pthread.h 头文件和一个线程库实现。

下载地址:ftp://sourceware.org/pub/pthreads-win32

源码结构包括了已经编译好的二进制Pre-built.2,源码pthreads.2,还有一个QueueUserAPCEx ,是一个alert的driver,编译需要DDK ,默认vs2010 没有安装。Windows Device Driver Kit NTDDK.h 需要额外单独安装。

2.windows环境下使用pthread

VS-工具-选项-项目和解决方案-VC++目录,右边引用文件添加目录***/include,库文件添加目录***/lib
下面①②选一种就可以
①然后在include pthread之后加句
#pragma comment(lib, "pthreadVC2.lib")
②或者在项目-属性-配置属性-链接器-常规-附加库目录,加进库目录
在项目-属性-配置属性-链接器-输入-附加依赖项,加进lib库名

注意事项:

在Windows下使用静态编译的pthread时要特别注意一下,必须显式的调用如下四个函数,否则pthread用到的一些全局变量会没有被初始化,导致所有的pthread的APIs调用都crash。

pthread_win32_process_attach_np (void);

pthread_win32_process_detach_np (void);

pthread_win32_thread_attach_np (void);

pthread_win32_thread_detach_np (void);

pthread官方代码在动态编译的版本中主动做了这个attach和detach操作。而静态编译版本由于没有一个合适的地方来做这件事,就将attach和detach的的操作扔给用户来完成了。

3.测试

#include<stdio.h>
#include<pthread.h>
#include<Windows.h>
#pragma comment(lib, "pthreadVC2.lib")  //必须加上这句
 
void*Function_t(void* Param)
{
     pthread_t myid = pthread_self();
     while(1)
     {
         printf("线程ID=%d \n", myid);
         Sleep(4000);
     }
     return NULL;
}
 
int main()
{
     pthread_t pid;
     pthread_create(&pid, NULL, Function_t,NULL);
     while (1)
     {
         printf("in fatherprocess!\n");
         Sleep(2000);
     }
     getchar();
     return 1;
}

4.参考资料

http://baike.baidu.com/link?url=_FRBxaMGMtQUtpKMJSpW42u9cvGv8VEUR4-WGuDxAIPaCjIzUH6ubC3kABl3ZVpt

http://www.cnblogs.com/ayanmw/archive/2012/08/06/2625275.html

http://www.rosoo.net/a/201108/14914.html