2014-09-29 83 views
1

我正在編寫一個多線程C++程序,遵循我用於測試的一個簡單函數。如果我在此註釋掉睡眠(),該程序將起作用。但是,如果我將sleep()放入循環中,屏幕上將不會有輸出,看起來sleep()會殺死整個執行過程。請幫忙。 sleep函數是否會終止pthread程序的執行?我怎樣才能睡眠線程?pthread sleep()函數停止整個執行

void *shop(void *array){ 
int second = difftime(time(0), start); 

// init shopping list with characters 
string *info = (string *)array; 
int size = stoi(info[0]); 
string character = info[1]; 
string career = info[2]; 

if (career == "Auror") { 
    int process = 3; 
    while (process < size+1) { 
     int shop = stoi(info[process]); 
     pthread_mutex_lock(&counter); 
     cout << process << endl; 
     sleep(1); 
     pthread_mutex_unlock(&counter); 
     process++; 
    } 
} 

輸出不睡覺是:

3 
4 
5 
6 
3 
4 
5 
6 

睡眠()的輸出是這樣的:

3 
3 

它打破while循環。

+0

我在測試時使用了兩個線程 – user3735448 2014-09-29 02:08:16

+0

您如何定義和初始化互斥對象? pthread_mutex_lock返回什麼? – 2014-09-29 06:07:26

+0

我這樣定義:pthread_mutex_t counter = PTHREAD_MUTEX_INITIALIZER;我的朋友告訴我,這可能是由於我把睡眠鎖在了鎖上。但是,我試圖將其移出,但它仍然不起作用,它只是打破了最初的執行 – user3735448 2014-09-29 06:36:11

回答

-2

是的,如果主線程死了,你的應用程序就會死亡,包括所有「工作線程」。

添加一個getchar()system("pause")或任何在您的主線程。

+0

或者直接調用'pthread_exit()'退出main。 – alk 2014-09-30 10:28:19

1

讓主線程等待子線程通過pthread_join完成其任務。 pthread_join()函數等待線程指定的線程終止。如果該線程已經終止,則pthread_join()立即返回。線程指定的線程必須可以連接。