C語言使用pthread多線程編程(windows系統)一

運行以前須要作一些配置: 
1.下載PTHREAD的WINDOWS開發包 pthreads-w32-2-4-0-release.exe(任何一個版本都可) 
   http://sourceware.org/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.C代碼 :
#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;  
}  

出處:http://jefry.iteye.com/blog/1102692windows

相關文章
相關標籤/搜索