在pthread中阻止当前线程

时间:2012-03-12 10:54:28

标签: 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);

我想阻止当前线程,这意味着暂停其执行。但在我看来,睡眠不起作用。甚至cpu_usage()函数也没有调用。 但在我看来f1的睡眠不起作用。你们能告诉我这是什么原因吗?

1 个答案:

答案 0 :(得分:3)

您是否加入了main的帖子?您必须在创建的线程上调用pthread_join。您的主线程可能会在由pthread_create创建的线程之前退出。如果您没有等待终止,sleep通话无效。

相关问题