linux多线程API函数
来源:互联网 发布:网络销售工作12小时 编辑:程序博客网 时间:2024/05/21 06:54
总结一下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);
}
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
}
#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;
}
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
- linux多线程API函数
- 多线程API函数
- Linux C——多线程的基本概念及API函数
- Linux多线程API
- linux 多线程API
- linux api 函数---mkdir
- Linux API函数大全
- Linux API函数总结
- Linux API函数总结
- Linux API函数总结
- Linux API函数总结
- Linux API函数总结
- Linux API函数总结
- Linux API函数总结
- Linux API函数总结
- Linux API函数大全
- Linux多线程函数解析
- Linux多线程函数解析
- 漫画HDFS工作原理
- Struts2实现文件上传和下载
- jpg在线转换pdf
- 代码诊断工具DTrace
- 车辆违章查询演示示例
- linux多线程API函数
- HDU 1728 逃离迷宫
- MTK8127_FB710项目调试长按power键重启改动
- 《数学之美》读书笔记和知识点总结
- Project之于项目管理[002]
- Android_Unicode码转为汉字
- 《从0开始学产品策划》第四期:第一次做需求从失败到成功
- 虚拟机WMware安装Fedora出现Your host's BIOS valid NUMA information错误
- 车辆违章查询演示示例