参考:http://bbs.51cto.com/thread-961753-1.html
1.下载pthreads-w32-2-8-0-release.exe文件,并解压到一个目录下。(下载地址:ftp://sourceware.org/pub/pthreads-win32/)
2. 找到include和lib文件夹,下面分别把它们添加到VC++6.0的头文件路径和静态链接库路径下面:
a).Tools->Options,选择Directory页面,然后在Show directories for:中选择Include files(默认)
在Directories中添加include的路径。在Show directories for:中选择Library files,
在Directories中添加lib的路径。
b).Project->Settings,选择Link页面,然后将lib下的*.lib文件添加到Object/library Modules,各lib文件以空格隔开。
c).将lib下的*.dll文件复制到工程目录下,即根目录。
3.代码
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <windows.h>
int piao = 100;
pthread_mutex_t mut;
void* tprocess1(void* args){
int a = 0;
while(true){
pthread_mutex_lock(&mut);
if(piao>0){
Sleep(1);
piao--;
printf("窗口1----------------还剩%d张票\n",piao);
}else{
a = 1;
}
pthread_mutex_unlock(&mut);
if(a == 1) {
break;
}
}
return NULL;
}
void* tprocess2(void* args){
int a = 0;
while(true){
pthread_mutex_lock(&mut);
if(piao>0){
Sleep(1);
piao--;
printf("窗口2----------------还剩%d张票\n",piao);
}else{
a = 1;
}
pthread_mutex_unlock(&mut);
if(a == 1) {
break;
}
}
return NULL;
}
void* tprocess3(void* args){
int a = 0;
while(true){
pthread_mutex_lock(&mut);
if(piao>0){
Sleep(1);
piao--;
printf("窗口3----------------还剩%d张票\n",piao);
}else{
a = 1;
}
pthread_mutex_unlock(&mut);
if(a == 1) {
break;
}
}
return NULL;
}
void* tprocess4(void* args){
int a = 0;
while(true){
pthread_mutex_lock(&mut);
if(piao>0){
Sleep(1);
piao--;
printf("窗口4----------------还剩%d张票\n",piao);
}else{
a = 1;
}
pthread_mutex_unlock(&mut);
if(a == 1) {
break;
}
}
return NULL;
}
int main(){
pthread_mutex_init(&mut,NULL);
pthread_t t1;
pthread_t t2;
pthread_t t3;
pthread_t t4;
pthread_create(&t4,NULL,tprocess4,NULL);
pthread_create(&t1,NULL,tprocess1,NULL);
pthread_create(&t2,NULL,tprocess2,NULL);
pthread_create(&t3,NULL,tprocess3,NULL);
Sleep(5000);
return 0;
}