pthread_create()函数
2013-11-13 13:08
423 查看
函数声明
int pthread_create(pthread_t*restricttidp,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
相关文章推荐
- pthread_create()和pthread_atfork()函数使用时应注意的问题
- 编写线程函数时,链接时报错:undefined refrence to 'pthread_create '
- linux编程之pthread_create函数
- pthread_create()函数样例
- Linux多线程函数pthread_create()函数
- C++使用线程函数pthread_create时,调用的成员函数要定义为静态成员函数
- c++里的 pthread_create 函数小结
- pthread_create()函数用法
- 基于pthread_create,readlink,getpid等函数的学习与总结
- pthread_create函数编译时报错:undefined reference to 'pthread_create'
- pthread_create 函数
- 类成员函数作为pthread_create函数参数
- pthread库中操作线程专有数据的函数:pthread_key_create,pthread_setspecific,pthread_gtespecific,pthread_key_delete
- linux函数之pthread_create
- 解决使用pthread_create函数造成的内存泄露
- pthread_create、readlink、getpid等函数的学习与总结
- 基于pthread_create,readlink,getpid等函数的学习与总结
- 版本加载一些用户态用法总结--pthread_create函数用法
- c++里的 pthread_create 函数小结
- 解决使用pthread_create函数造成的内存泄露