gpt4 book ai didi

c++ - 在 pthread 中阻塞当前线程

转载 作者:太空宇宙 更新时间:2023-11-04 02:14:27 25 4
gpt4 key购买 nike

我为一个小测试编写了以下代码片段,

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com