您的位置:首页 > 其它

pthread_create()函数

2013-11-13 13:08 423 查看

函数声明

  int pthread_create(pthread_t*restrict
tidp,const pthread_attr_t
*restrict_attr,void*(*start_rtn)(void*),void *restrict arg);

参数

attr参数用于指定各种不同的线程属性。新创建的线程从start_rtn函数的地址开始运行,该函数只有一个万能指针参数arg,如果需要向start_rtn函数传递的参数不止一个,那么需要把这些参数放到一个结构中,然后把这个结构的地址作为arg的参数传入。(百科),要注意,把这些参数放在一个结构中,一定也要在函数start_rtn()中这么做,也就是说这个参数在两个函数中一致。参考下面例子
 

返回值

  若成功则返回0,否则返回出错编号   返回成功时,由tidp指向的内存单元被设置为新创建线程的线ID。 

linux下用C开发多线程程序,Linux系统下的多线程遵循POSIX线程接口,称为pthread。

//sub_add.c实现加法和减法并行运算

#include

#include

struct arg{

int x;

int y;

};

void add(struct arg *ag)

{

printf("%d+%d=%d\n",ag->x,ag->y,ag->x+ag->y);

return;

}

void sub(struct arg*ag)

{

printf("%d-%d=%d\n",ag->x,ag->y,ag->x-ag->y);

return;

}

int main()

{

pthread_t
tid1,tid2;

printf("input two number:");

struct arg
ag;

scanf("%d
%d",&ag.x,&ag.y);

pthread_create(&tid1,NULL,(void*)add,&ag);

pthread_create(&tid2,NULL,(void*)sub,&ag);

printf("child1 thread id:%u\nchild2 thread
id:%u\n",tid1,tid2);

sleep(2);

printf("main
thread id:%u\nprocess id:%d\n",pthread_self(),getpid());

return
0;

}

编译语句:gcc sub_add.c -o test -lpthread

运行语句:./test
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: