2012-03-12 62 views
1

块当前线程我写了下面的代码片断为一个小的测试,在并行线程

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的睡眠不起作用。你们能告诉我是什么原因吗?

+0

你为什么觉得'sleep()'不工作?你有计时吗? – trojanfoe 2012-03-12 10:56:36

+0

,因为如果我省略了睡眠(1),它需要相同的时间。 – 2012-03-12 10:57:54

+1

内核调度可能是一个问题。将时间代码放入线程代码中,并将开始和结束时间打印到'stdout'。 – trojanfoe 2012-03-12 10:59:06

回答

3

你加入了你的线程main?你必须在创建的线程上调用pthread_join。您的主线程可能在线程之前退出,由pthread_create创建。如果您不等待终止,sleep呼叫不起作用。