簡體   English   中英

pthread sleep()函數停止整個執行

[英]pthread sleep() function stop whole execution

我正在編寫一個多線程c ++程序,遵循一個我用於測試的簡單函數。 如果我在那里注釋掉sleep(),該程序將起作用。 但是,如果我將sleep()放入循環中,則屏幕上將不會顯示任何輸出,似乎sleep()會殺死整個執行過程。 請幫忙。 睡眠功能會終止pthread程序的執行嗎? 我該如何睡覺呢?

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

sleep()的輸出類似於:

3
3

它打破了while循環。

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

是的,如果主線程死亡,那么您的應用程序將死亡,包括所有“工作線程”。

在您的主線程中添加一個getchar()system("pause")或其他內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM