红联Linux门户
Linux帮助

求教:c简单线程的问题

发布时间:2008-05-22 14:45:46来源:红联作者:linx053848
我写了个简单多线程的程序,目的是在线程中计算一个面积,然后输出结果。但是运行之后发现我线程中调用的函数(void calculate(void *area))好像根本没执行。十分不解。程序如下:

#include
#include
#include
#include

void calculate(void *area){

printf("pthread\n");
float r = 2.0;
sleep(1);
*(float *)area = 3.14*r*r;
printf("pthread area = %f\n", *(float *)area);
pthread_exit(NULL);
}

int main(){

int ret;
void *p;
p = malloc(sizeof(float));
pthread_t id;
ret = pthread_create(&id, NULL, (void *)calculate, p);

if(ret != 0){

printf("error\n");
exit(1);
}
if(ret != 0){ /*note this is important!*/

pthread_join(id, NULL);
printf("thread is finished\n");
}
printf("thread is finished\n");
printf("area = %f\n", *(float *)p);
free(p);
exit(0);
}
该程序输出结果为thread is finished
area = 0.000000

请大虾们赐教,谢过了,这个程序让我很郁闷(6)m:b
文章评论

共有 3 条评论

  1. donghai1987 于 2008-05-25 15:20:41发表:

    支持楼上

  2. gongji110 于 2008-05-23 16:52:33发表:

    同意楼上

  3. colorrat 于 2008-05-22 23:59:59发表:

    if(ret != 0){ /*note this is important!*/
    pthread_join(id, NULL);
    printf("thread is finished\n");
    }

    这里应该是if(ret == 0) 而不是(ret != 0)