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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章