我正在編寫一個多線程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循環。
我在測試時使用了兩個線程 – user3735448 2014-09-29 02:08:16
您如何定義和初始化互斥對象? pthread_mutex_lock返回什麼? – 2014-09-29 06:07:26
我這樣定義:pthread_mutex_t counter = PTHREAD_MUTEX_INITIALIZER;我的朋友告訴我,這可能是由於我把睡眠鎖在了鎖上。但是,我試圖將其移出,但它仍然不起作用,它只是打破了最初的執行 – user3735448 2014-09-29 06:36:11