我想創建一個數字,都必須等待所有線程被創建,纔可以執行任何操作不同的線程在pthread_create()的說法。這是一個大型計劃的一小部分,我只是試圖採取步驟。當每個線程被創建時,它立即被信號量阻塞。所有線程創建完畢後,我循環並釋放所有線程。然後,我希望每個線程都打印出它的線程號碼,以驗證它們全部等待。我只允許一個線程使用另一個信號量一次打印。問題與POSIX線程同步和/或通過
我遇到的問題是,雖然我創建線程#1-10,一個線程打印,這是#11。另外,有幾個線程說他們有與另一個相同的號碼。在傳遞線程ID時出現錯誤還是以某種方式在我的同步中出現錯誤?
下面是相關代碼:
//Initialize semaphore to 0. Then each time a thread is spawned it will call
//semWait() making the value negative and blocking that thread. Once all of the
//threads are created, semSignal() will be called to release each of the threads
sem_init(&threadCreation,0,0);
sem_init(&tester,0,1);
//Spawn all of the opener threads, 1 for each valve
pthread_t threads[T_Valve_Numbers];
int check;
//Loop starts at 1 instead of the standard 0 so that numbering of valves
//is somewhat more logical.
for(int i =1; i <= T_Valve_Numbers;i++)
{
cout<<"Creating thread: "<<i<<endl;
check=pthread_create(&threads[i], NULL, Valve_Handler,(void*)&i);
if(check)
{
cout <<"Couldn't create thread "<<i<<" Error: "<<check<<endl;
exit(-1);
}
}
//Release all of the blocked threads now that they have all been created
for(int i =1; i<=T_Valve_Numbers;i++)
{
sem_post(&threadCreation);
}
//Make the main process wait for all the threads before terminating
for(int i =1; i<=T_Valve_Numbers;i++)
{
pthread_join(threads[i],NULL);
}
return 0;
}
void* Valve_Handler(void* threadNumArg)
{
int threadNum = *((int *)threadNumArg);
sem_wait(&threadCreation);//Blocks the thread until all are spawned
sem_wait(&tester);
cout<<"I'm thread "<<threadNum<<endl;
sem_post(&tester);
}
當T_Valve_Numbers = 10,一些示例輸出:
Creating thread: 1
Creating thread: 2
Creating thread: 3
Creating thread: 4
Creating thread: 5
Creating thread: 6
Creating thread: 7
Creating thread: 8
Creating thread: 9
Creating thread: 10
I'm thread 11 //Where is 11 coming from?
I'm thread 8
I'm thread 3
I'm thread 4
I'm thread 10
I'm thread 9
I'm thread 7
I'm thread 3
I'm thread 6
I'm thread 6 //How do I have 2 6's?
OR
Creating thread: 1
Creating thread: 2
Creating thread: 3
Creating thread: 4
Creating thread: 5
Creating thread: 6
Creating thread: 7
Creating thread: 8
Creating thread: 9
Creating thread: 10
I'm thread 11
I'm thread 8
I'm thread 8
I'm thread 4
I'm thread 4
I'm thread 8
I'm thread 10
I'm thread 3
I'm thread 9
I'm thread 8 //Now '8' showed up 3 times
「我線程......」打印10次,看起來像我的信號量讓所有線程通過。我只是不確定爲什麼他們的線程數目被搞砸了。
傳的我,而不是它的地址的值,到線程。 – Kevin 2014-10-19 16:04:47
正如我下面所說的,我必須傳遞一個'void *'類型,而我的編譯器不允許我直接從int中進行投射。我無法找到/想出任何其他方式。 – art3m1sm00n 2014-10-19 16:10:36