pthread_create的浅析

看下面代码,你是否能得出正确答案呢?

#include<stdio.h>
#include<string.h>
#include <pthread.h>
  
void* print1(void* data){
    printf("1 ");
}
  
void* print2(void* data){
    printf("2 ");
}
 
void* print3(void* data){
    printf("3 ");
}
 
int main(void){
    pthread_t t,t1,t2;
     
    pthread_create(&t,0,print1,NULL);
    pthread_create(&t1,0,print2,NULL);
    pthread_create(&t2,0,print3,NULL);
     
    pthread_join(t,NULL);
    pthread_join(t1,NULL);
    pthread_join(t2,NULL);
    printf("\n");
}

此刻,你将提出pthread_create和pthread_join到底是什么呢?

接下来,我们就来看一看。

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用来等待一个线程的结束。

头文件 : #include <pthread.h>

函数定义: 

int pthread_join(pthread_t thread, void **retval);

描述 :pthread_join()函数,以阻塞的方式等待thread指定的线程结束。当函数返回时,被等待线程的资源被收回。如果线程已经结束,那么该函数会立即返回。并且thread指定的线程必须是joinable的。

参数 :thread: 线程标识符,即线程ID,标识唯一线程。retval: 用户定义的指针,用来存储被等待线程的返回值。

返回值 : 0代表成功。 失败,返回的则是错误号。


好了,我们已经了解了上面两个函数,我们现在来看看这个题。

pthread_join(t,NULL)意思是等待线程t执行结束了再执行下面的代码。但在这之前,3个线程都已提交,它们可能都已经顺序随机地执行了,也可能没有,所以结果也是不可预测的。

如果想更进一了解它的用法,可以看看http://blog.csdn.net/tommy_wxie/article/details/8545253

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值