簡介
linux的線程庫是Pthread,代碼需要包含<pthread.h>頭文件,編譯裏需要添加-pthread參數。
函數介紹
線程句柄
pthread_t
線程創建函數
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg);
第一個參數 線程句柄
第二個參數 線程屬性
第三個參數 線程運行函數
第四個能數 傳到線程裏的參數
創建成功返回0,否則返回錯誤代碼
等待線程運行結束函數
int pthread_join(thread_t tid, void **status);
創建成功返回0,否則返回錯誤代碼
代碼目標
創建多個線程,給每個線程一個號碼,然後線程將獲取的號碼打印出來。
代碼
#include<pthread.h>
#include<stdio.h>
#include<cstdlib>
void *threadFuntion(void *arg){
int *threadNum=(int *)arg;
printf("線程獲取的號碼:%d\n",*threadNum);//將號碼輸出
(*threadNum)++;
}
int main(){
int i,j;
printf("演繹linux多線程.第一篇 \n");
printf("by 第XXX個小號 原文(http://blog.csdn.net/ccy0815ccy) \n");
const int N=10;
pthread_t threadID[N];//線程ID
int threadNum=0;//線程獲取的號碼
for(i=0;i<N;i++){
pthread_create(&threadID[i],NULL,threadFuntion,&threadNum);//將號碼傳給線程
}
for(j=0;j<N;j++)
pthread_join(threadID[j],NULL);//等待線程運行結束
printf("運行完成後threadNum的值:%d",threadNum);
return 0;
}
運行結果
分析
不同的線程獲取的相同的號碼。子線程是並行的,可能threadNum被同時輸出,也就是對threadNum變量的同時訪問,此時threadNum被稱爲臨界資源,對臨界資源進行操作的相關代碼段稱爲臨界區。這是線程中經典互斥問題。將在以後的文章中討論
轉載請標明出處,原文http://blog.csdn.net/ccy0815ccy