我正在编写一个多线程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