linux创建线程之pthread_create

 

说明:本文转自多线程编程之pthread_create函数应用,在此基础上笔者做了些许改动。

                             pthread_create函数

函数简介

  pthread_create是UNIX环境创建线程函数

头文件

  #include<pthread.h>

函数声明

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

返回值

  若成功则返回0,否则返回出错编号

参数

  第一个参数为指向线程标识符的指针。

  第二个参数用来设置线程属性。

  第三个参数是线程运行函数的地址。

  最后一个参数是运行函数的参数。

注意

  在编译时注意加上-lpthread参数,以调用静态链接库。因为pthread并非Linux系统的默认库。 

                             pthread_join函数

函数简介

  函数pthread_join用来等待一个线程的结束。

函数原型为:

  extern int pthread_join __P (pthread_t __th, void **__thread_return);

参数:

  第一个参数为被等待的线程标识符

  第二个参数为一个用户定义的指针,它可以用来存储被等待线程的返回值。

注意

    这个函数是一个线程阻塞的函数,调用它的函数将一直等待到被等待的线程结束为止,当函数返回时,被等待线程的资源被收回。如果执行成功,将返回0,如果失败则返回一个错误号。

例子:

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 #include<pthread.h>
 4 
 5 /* 声明结构体 */
 6 struct member
 7 {
 8     int num;
 9     char *name;
10 };     
11 
12 /* 定义线程pthread */
13 static void * pthread(void *arg)       
14 {
15     struct member *temp;
16     
17     /* 线程pthread开始运行 */
18     printf("pthread start!\n");
19     
20     /* 令主线程继续执行 */
21     sleep(2);
22     
23     /* 打印传入参数 */
24     temp = (struct member *)arg;      
25     printf("member->num:%d\n",temp->num);
26     printf("member->name:%s\n",temp->name);
27     
28     return NULL;
29 }
30 
31 /* main函数 */
32 int main(int agrc,char* argv[])
33 {
34     pthread_t tidp;
35     struct member *b;
36 
37     /* 为结构体变量b赋值 */
38     b = (struct member *)malloc(sizeof(struct member));           
39     b->num=1;
40     b->name="mlq";              
41 
42     /* 创建线程pthread */
43     if ((pthread_create(&tidp, NULL, pthread, (void*)b)) == -1)
44     {
45         printf("create error!\n");
46         return 1;
47     }
48     
49     /* 令线程pthread先运行 */
50     sleep(1);
51     
52     /* 线程pthread睡眠2s,此时main可以先执行 */
53     printf("mian continue!\n");
54     
55     /* 等待线程pthread释放 */
56     if (pthread_join(tidp, NULL))                  
57     {
58         printf("thread is not exit...\n");
59         return -2;
60     }
61     
62     return 0;
63 }

编译与执行结果

    编译与执行结果如下图所示,可以看到主线程main和线程pthread交替执行。也就是说是当我们创建了线程pthread之后,两个线程都在执行,证明创建成功。另外,可以看到创建线程pthread时候,传入的参数被正确打印。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值