linux线程系列(3)线程创建
来源:互联网 发布:网络没问题游戏上不去 编辑:程序博客网 时间:2024/05/29 10:40
线程创建函数如下:
#include <pthread.h>
int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void*), void *restrict arg);
返回: 成功返回0,否则返回错误编号
参数
tidp:线程标识符指针
attr:线程属性指针start_rtn:线程运行函数的起始地址
arg:传递给线程运行函数的参数注意:新创建线程从start_rtn函数的地址开始运行,但不能保证新线程和调用线程的执行顺序。
实例代码:创建两个子线程
#include <pthread.h>#include <stdio.h>#include <stdlib.h>#include <math.h>#include <unistd.h>typedef struct{ char name[20]; int time; int start; int end;}RaceArg;void* th_fn(void *arg){ RaceArg *r = (RaceArg *)arg; int i = r->start; for(; i <= r->end; i++) { printf("%s(%lx) run %d\n", r->name, pthread_self(), i); usleep(r->time);//微秒 } return (void*)0;}int main(){ int err; pthread_t rabbit, turtle; RaceArg r_a = {"rabbit", (int)(drand48()*100000), 20, 50}; RaceArg t_a = {"turtle", (int)(drand48()*100000), 20, 50}; if((err = pthread_create(&rabbit, NULL, th_fn, (void*)&r_a)) != 0) { perror("pthread create error"); } if((err = pthread_create(&turtle, NULL, th_fn, (void*)&t_a)) != 0) { perror("pthread create error"); } pthread_join(rabbit, NULL); pthread_join(turtle, NULL); printf("control thread id: %lx\n", pthread_self()); printf("finished!\n"); return 0;}
对于以上的代码内存空间分配图如下(假设g_v是一个全局变量):
主线程启动的两个子线程拥有自己的栈空间,子线程各种栈空间中的局部变量是子线程私有的,外部不可访问(子线程的局部变量i,r都存储在私有的栈中)。对于数据段和堆中的数据是主线程和两个子线程共享的,因此为了安全起见,子线程尽量使用局部变量,保证线程的变量不被其它线程修改。(子线程如果申请内存空间,会分配到堆空间,堆空间是共享的,这点需要注意)
阅读全文
0 0
- linux线程系列(3)线程创建
- linux线程系列(4)线程终止
- Linux 线程(1)线程创建
- 线程(创建线程)
- linux 线程编程:线程创建
- linux线程系列(2)linux线程分类
- Linux线程-创建
- linux 下创建线程
- LINUX 创建线程例子
- linux 内核线程创建
- linux 创建线程
- Linux创建线程
- Linux创建线程
- linux下创建线程
- linux创建线程
- Linux创建子线程
- Linux线程的创建
- linux内核线程 [创建]
- LeetCode题解(Week 13):128. Longest Consecutive Sequence
- JAVA中常用的4种线程池的使用
- 【java基础】JDBC实现增删改查
- java面试常用算法题深入剖析之兔子繁殖问题
- opencv2 预测算法之Kalman滤波器(KalmanFilter)
- linux线程系列(3)线程创建
- could not calculate build plan:插件版本问题
- 学习笔记一--Weex介绍
- Binder
- MyEclipse+Maven+Tomcat搭建环境和项目配置
- MVP mvc
- 搜索-B
- Spring Security(01)——初体验
- AppCache