pthread_create()函数

函数声明

  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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值