我为一个小测试编写了以下代码片段,
i=1;
static void *f1(void *p)
{
if(cpu_usage()>50)
{
//this sleep is not working and thread is not entering this condition eventhough the cpu_usage() returns more than 50
sleep(5);
}
while (i==0) {
//i=0;
//cout<<"inside"<<endl;
}
i=0;
//do work
i=1;
printf("i's value has changed to %d.\n", i);
return NULL;
}
然后我用线程对象分配了函数,
int rc = pthread_create(&pthread1, NULL, f1, NULL);
我想阻塞当前线程,也就是暂停它的执行。但在我看来, sleep 不起作用。甚至 cpu_usage() 函数也没有调用。 但在我看来,f1 中的 sleep 不起作用。你们能告诉我是什么原因吗?
最佳答案
您是否从 main
加入了您的线程?您必须在创建的线程上调用 pthread_join
。您的主线程可能在由 pthread_create
创建的线程之前退出。如果您不等待它终止,sleep
调用无效。
关于c++ - 在 pthread 中阻塞当前线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9665770/