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

标签 c++ c multithreading pthreads

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

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/

相关文章:

c++ - atomic_compare_exchange 与互斥锁

c++ - glMapBufferRange(...) 中的偏移量与 glDrawArraysInstanced(...) 中的第一个偏移量的关系

c - 无符号整型溢出

c++ - 关于 malloc 和 new 在各自处理内存分配的机制方面的区别?

c++ - 分离的 std::thread 终止后是否需要删除?

android - 该应用程序显示即使在后台线程中执行了操作,也在主线程中做了过多的工作

c++ - 将对象传递给以指针为参数的函数

c++ - 我应该如何将 SSE 数据传递给我的函数/运算符(operator)?

c++ - 何时在空实例上调用成员函数会导致未定义的行为?

c - 迭代任意内存和可能的对齐问题