2010-11-24 119 views
0

我想創建線程使用pthread_create.The線程,從他們的開始例程,'cout'到控制檯後創建一個簡單的味精。我試圖打印線程ID也從主功能。 我的代碼是:線程:pthread_create()輸出混淆

#include <iostream> 
#include <pthread.h> 
#include <sstream> 
#include <string> 
using namespace std; 


void* start_proc(void* threadNo) 
{ 




    pthread_mutex_t display; 


    if(pthread_mutex_init(&display, NULL) != 0) { 

    exit(-1); 
    } 

    pthread_mutex_lock(&display); 

    stringstream buf; 

    buf<<"Initialized threadNo = "<<*((int*)threadNo); 
    buf<<endl; 

    cout<<buf.str(); 

    pthread_mutex_unlock(&display); 

    pthread_exit(NULL); 

    return(0); 
} 

int main() 
{ 



    int i =0; 
    int k =0; 


    pthread_t threadCount[5]; 

    for(k=0; k<5; k++) 
    { 
     int* ptr = &k; 
     int errorCode=pthread_create(&threadCount[k], NULL, start_proc, (void*)ptr); 



    pthread_mutex_t display2; 

    if(pthread_mutex_init(&display2, NULL) != 0) { 

    exit(-1); 
    } 



     pthread_mutex_lock(&display2); 

     stringstream buf2; 

     buf2<<"threadCount "<<threadCount[k]; 
     buf2<<endl; 

     cout<<buf2.str(); 

     pthread_mutex_unlock(&display2); 




     if(errorCode) 
     { 
    cout<<"Error: return code from pthread_create= "<<errorCode<<endl; 

exit(-1); 

} 

    } 

    pthread_exit(NULL); 

return(0); 

} 

現在,當我運行的a.out多次一前一後,我得到

初始化爲threadno = 0
THREADCOUNT 2
THREADCOUNT 3
初始化threadNo = 1
threadCount 4
初始化爲threadno = 2
THREADCOUNT 5
初始化爲threadno = 4
初始化爲threadno = 4
THREADCOUNT 6

初始化爲threadno = 0
THREADCOUNT 2
THREADCOUNT 3
初始化爲threadno = 1
THREADCOUNT 4
threadCount 5
初始化threadNo = 3
THREADCOUNT 6
初始化爲threadno = 4
初始化爲threadno = 5

THREADCOUNT 2
THREADCOUNT 3
THREADCOUNT 4
THREADCOUNT 5
THREADCOUNT 6
初始化爲threadno = 5
初始化爲threadno = 5
初始化threadNo = 5
初始化adNo = 5
初始化爲threadno = 5

每次我運行它,我得到一些不同的pattern.Can別人的幫助,並解釋這是爲什麼? 我先不要mutexing清點,然後我在網上查找並納入,要儘量使線程安全

回答

1
  1. pthread_mutex_t display;是在線程函數中的局部(以及在main::for),所以每個線程鎖並解鎖不同的互斥鎖。

  2. 您將k的地址傳遞給線程函數,對於第一個線程,它與第五個線程的地址相同。

+0

第一點的Thanx.Indeed.Tha互斥體應該已經在全局聲明,即在文件範圍內,也應該從main()內初始化一次。 – rakeshd 2010-11-25 06:43:54