vs2010 使用pthread进行多线程编程

来源:互联网 发布:高帮男鞋 知乎 编辑:程序博客网 时间:2024/06/16 09:49

1、从http://sourceware.org/pthreads-win32/下载pthread windows安装包,我下的是pthread-w32-2-9-1-release.zip,其他版本也可以。解压到pthread-w32-2-9-1-release

2、打开vs2010,项目->属性->配置属性->VC++目录,包含目录里添加inlude路径,如下图所示,如果刚下载的压缩包放在D盘,则在包含目录那一栏添加:D:\pthread-w32-2-9-1-release\Pre-built.2\include;在库目录那一栏添加:D:\pthrea-w32-2-9-1-release\Pre-built2\lib

 

3、在链接器—>输入,附加依赖项一栏添加

pthreadVC2.lib;pthreadVCE2.lib;pthreadVSE2.lib;如下图所示。所有设置完成后点确定。

 

4、打开pthread-w32-2-9-1-release\Pre-built.2\lib\X86,将里面三个*.lib文件复制到你所建立的工程目录中去,这样就设置好了,大功告成。

如下一个简单的程序实例。

#include<stdio.h>#include<stdlib.h>#include<pthread.h>#define NUM_THREADS 4typedef struct{int threadId;}threadParm_t;void *threadFunc(void *parm){threadParm_t *p=(threadParm_t *)parm;fprintf(stdout,"Hello world from thread%d\n",p->threadId);pthread_exit((void *)&(p->threadId));return 0;}int main(int argc,char *argv[]){int i;int *res;res=(int *)malloc(sizeof(int));pthread_t thread[NUM_THREADS];threadParm_t threadParm[NUM_THREADS];for(i=0;i<NUM_THREADS;i++){threadParm[i].threadId=i;pthread_create(&thread[i],NULL,threadFunc,(void *)&threadParm[i]);}for(i=0;i<NUM_THREADS;i++){pthread_join(thread[i],(void **)&res);fprintf(stdout,"Thread %d has exited.\n",*res);}system("pause");return 0;}


运行程序得到如下结果。

 


如果运行时,提示缺少“pthreadVC2.dll”,将pthread目录下的pthreadVC2.dll文件拷贝到C:\Windows\System32(32位系统)中即可

 

0 0
原创粉丝点击