pthread-win32配置方法及pthread_mutex测试

来源:互联网 发布:网络口碑营销例子 编辑:程序博客网 时间:2024/06/06 01:06

1.下载pthreads-w32-2-8-0-release.exe

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


2. 安装pthreads-w32-2-8-0-release.exe

       双击pthreads-w32-2-8-0-release.exe,点击Browse选择安装到的目录,然后点击Extract解压,完成后点击Done。

       之后会在安装目录看到有三个文件夹Pre-built.2、pthreads.2、QueueUserAPCEx.

第一个是生成库(头文件和库文件那些),第二个是源码,第三个不清楚,像是测试程序。

       将Pre-built.2文件夹下的include和lib文件夹里的文件复制到VS2008对应的include和lib目录,我这里是C:\Program Files\Microsoft Visual Studio 9.0\VC\include和C:\Program Files\Microsoft VisualStudio 9.0\VC\lib.


//测试代码

#include <iostream>#include<stdlib.h>#include<stdio.h>#include "unistd.h"#include<pthread.h>typedef struct ct_sum{ int sum;pthread_mutex_t lock;}ct_sum;int i = 0;void * add1(void * cnt){     //此处如果注释掉该加锁,那么处理器就会一会处理线程1,一会处理线程2,i的值有可能出现不是递增,sum的最后结果也有可能不正确pthread_mutex_lock(&(((ct_sum*)cnt)->lock));//加锁for(;i<50;i++){(*(ct_sum*)cnt).sum+=i;printf("pthread 1 : i = %d, sum = %d \n",i,(*(ct_sum*)cnt).sum);}pthread_mutex_unlock(&(((ct_sum*)cnt)->lock));pthread_exit(NULL);//终止调用它的线程并返回一个指向某个对象的指针。return 0;}void * add2(void *cnt){     cnt= (ct_sum*)cnt;pthread_mutex_lock(&(((ct_sum*)cnt)->lock));for( ;i<101;i++){    (*(ct_sum*)cnt).sum+=i;printf("pthread 2 : i = %d, sum = %d \n",i,(*(ct_sum*)cnt).sum);}pthread_mutex_unlock(&(((ct_sum*)cnt)->lock));pthread_exit(NULL);return 0;}int main(void){ pthread_t ptid1,ptid2;int sum=0;ct_sum cnt;pthread_mutex_init(&(cnt.lock),NULL);//初始化锁变量mutex。attr为锁属性,NULL值为默认属性。cnt.sum=0;pthread_create(&ptid1,NULL,add1,&cnt);//创建线程pthread_create(&ptid2,NULL,add2,&cnt);pthread_mutex_lock(&(cnt.lock));//加锁printf("sum %d\n",cnt.sum);pthread_mutex_unlock(&(cnt.lock));//解锁pthread_join(ptid1,NULL);//以阻塞的方式等待thread指定的线程结束。当函数返回时,被等待线程的资源被收回。如果进程已经结束,那么该函数会立即返回pthread_join(ptid2,NULL);pthread_mutex_destroy(&(cnt.lock));//销毁锁变量return 0;} 

unistd.h

/** This file is part of the Mingw32 package.*  unistd.h maps     (roughly) to io.h*/#ifndef _UNISTD_H#define _UNISTD_H#include <io.h>#include <process.h>#endif /* _UNISTD_H */


0 0
原创粉丝点击