linux多线程API函数

总结一下linux多线程编程用到的几个API函数

一、pthread_create

 具体格式:
  #include<pthread.h>
  int pthread_create(pthread_t *—thread,_const pthread_attr_t *attr,void*(*start_rtn)(void*),void *arg);
  返回值:若成功则返回0,否则返回出错编号
  新创建的线程从start_rtn函数的地址开始运行,该函数只有一个无指针参数arg,如果需要向start_rtn函数传递的参数不止一个,那么需要把这些参数放到一个结构中,然后把这个结构的地址作为arg的参数传入。创建线程后, 原来的主线程继续执行下一个代码。

     例如主线程:

 int data=23;
 ret=pthread_create(&id,NULL,(void *)thread,(void *)data);//这个void*一定要有

     子线程:

void thread(arg){
 printf("this is the slave process %d /n",arg);
}
//arg=23;
如果传递多个参数,用结构体。

 

二、pthread_join

 

pthread_join使一个线程等待另一个线程结束。

代码中如果没有pthread_join主线程会很快结束从而使整个进程结束,从而使创建的线程没有机会开始执行就结束了。加入pthread_join后,主线程会一直等待直到等待的线程结束自己才结束,使创建的线程有机会执行。

所有线程都有一个线程号,也就是Thread ID。其类型为pthread_t。通过调用pthread_self()函数可以获得自身的线程号。

(上段文字说明摘自百度空间-学习苦旅: http://hi.baidu.com/beisika/blog/item/8ced51cea7ac9c3eb600c8ea.html)
      我自己做了测试,下面是源代码:
#include <stdio.h>
#include <pthread.h>
void thread(arg){
 int i;
 sleep(3);
 for(i=0;i<2;i++)  
 printf("this is the slave process %d /n",arg); // code1
}
int main(void){
 pthread_t id;
 int i ,ret;
 int data=23;
 ret=pthread_create(&id,NULL,(void *)thread,(void *)data);
 if(ret!=0)
 {
 printf("create fail/n");
 exit(1);
 }
 for(i=0;i<4;i++)
 printf("This is the main process %d /n",i); 
  pthread_join(id,NULL);
 return 0;
}
测试的关键是在子线程中用sleep(3)函数。注释掉pthread_join则code1来不急执行;不注释可以执行。
如果没有sleep函数,则此区别看不出来。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值