2016-03-06 60 views
0

以下程序的問題是主線程在其他線程有機會顯示其結果之前結束。另一個問題是線程顯示不正確。線程編程問題

的輸出要求是:

This is thread 0. 
This is thread 1. 
This is thread 2. etc. 

代碼:

#include <stdlib.h> 
#include <stdio.h> 
#include <unistd.h> 
#include <pthread.h> 
#include <time.h> 
void *text(void *arg); 
long code[] = { 4, 6, 3, 1, 5, 0, 2 }; // Order in which to start threads 
int num = 0; 
int main() 
{ 
int i; 
pthread_t tid[7]; 
// Initialize random number generator 
time_t seconds; 
time(&seconds); 
srand((unsigned int) seconds); 
// Create our threads 
for (i = 0; i < 7; i++) 
pthread_create(&tid[i], NULL, text, (void*)code[i]); 
// Exit main 
return 0; 
} 
void *text(void *arg) 
{ 
long n = (long)arg; 
int rand_sec = rand() % (3 - 1 + 1) + 1; // Random num seconds to sleep 
while (num != n) {} // Busy wait used to wait for our turn 
num++; // Let next thread go 
sleep(rand_sec); // Sleep for random amount of time 
printf("This is thread %d.\n", n); 
// Exit thread 
pthread_exit(0); 
} 

任何人都可以使用互斥來解決同步問題幫助嗎?

+0

你的序列化要求就像是要求你的新車裝上方形的車輪,而且無論如何,互斥對於這種情況來說都是不恰當的機制。 –

+0

您可以使用障礙來同步修復線程查殺問題的所有線程。此外,還沒有任何已知的線程順序對齊方法。它首先殺死了線程的目的。您需要明確使用共享內存來發出線程串行打印序列的信號。 – jada12276

+0

基本上,通過應用互斥鎖和同步,您正在消除您可能具有的多線程優勢。通常它會比其對應的單線程應用程序慢。關於在任何線程完成之前退出應用程序的第二個問題,可以使用join在退出之前等待所有線程完成。 – Saleem

回答

4

您可以使用pthread_join使main例程等待,直到其他線程完成爲止,例如,

int main() 
{ 
int i; 
pthread_t tid[7]; 
// Initialize random number generator 
time_t seconds; 
time(&seconds); 
srand((unsigned int) seconds); 
// Create our threads 
for (i = 0; i < 7; i++) 
    pthread_create(&tid[i], NULL, text, (void*)code[i]); 
for(i = 0; i < 7; i++) 
    pthread_join(tid[i], NULL); 
// Exit main 
return 0; 
} 

此外,您的代碼等待num是當你開始在打開的優化線程ID可能有一些問題。你num變量應聲明volatile如果線程之間共享的,就像這樣:

volatile int num; 

這就是說,忙等待num像這樣非常,非常低效。當num發生變化時,您應該考慮使用條件變量來通知線程,以便他們可以檢查它是否輪到他們一次,然後是否睡覺。查看所有pthread_cond_*函數以獲取更多信息。

+2

['volatile'不適用於多線程](http://stackoverflow.com/questions/2484980/why-is-volatile-not-considered-useful-in-multithreaded-c-or-c-programming)。您應該使用適當的原子數據類型,如[C11 atomics](http://en.cppreference.com/w/c/atomic)。 – ComicSansMS