linux创建线程
2015-09-19 23:27
405 查看
线程:
进程:资源分配的基本单位
线程:系统调度的基本单位
线程创建: pthread_create (&tid 返回子线程ID, 属性,子线程函数入口(函数指针),函数传入参数)
sqrt :-lm --> - link libm.a
pthread:-lpthread -> -link libpthread.a
线程创建时候要注意属性:
优先级 、调度、分离状态(detach? joined?)、栈大小及起始地址,没有特殊要求就设成NULL
系统默认是个join线程,非分离
子线程函数入口 是有返回值void *的, 也可以传入参数,具体的参数类型是第四个参数传入
线程的回收: 只针对的是非分离线程 pthread_join
注意: 1:主线程会先继续执行;
如果主线程没有等待回收或者其它阻塞,主线程结束的时候,整个进程也就结束了
2:如果线程中调用了exit类的函数,会直接退出整个进程;
return (void *)0 ; 则返回到调用的线程中。
实例:
进程:资源分配的基本单位
线程:系统调度的基本单位
线程创建: pthread_create (&tid 返回子线程ID, 属性,子线程函数入口(函数指针),函数传入参数)
sqrt :-lm --> - link libm.a
pthread:-lpthread -> -link libpthread.a
线程创建时候要注意属性:
优先级 、调度、分离状态(detach? joined?)、栈大小及起始地址,没有特殊要求就设成NULL
系统默认是个join线程,非分离
子线程函数入口 是有返回值void *的, 也可以传入参数,具体的参数类型是第四个参数传入
线程的回收: 只针对的是非分离线程 pthread_join
注意: 1:主线程会先继续执行;
如果主线程没有等待回收或者其它阻塞,主线程结束的时候,整个进程也就结束了
2:如果线程中调用了exit类的函数,会直接退出整个进程;
return (void *)0 ; 则返回到调用的线程中。
实例:
#include <stdio.h> #include <pthread.h> #include <stdlib.h> int a=0; void *myThread1(void) { int i; for(i=0; i<3; i++) { a++; printf("pthread1: a=%d ",a); printf("This is the 1st pthread,pid is %d;tid1=%lu\n",getpid(),pthread_self()); sleep(1);//Let this thread to sleep 1 second,and then continue to run return (void *)0;// exit (0); } } void *myThread2(void) { int i; for (i=0; i<3; i++) { a++; printf("pthread2: a=%d ",a); printf("This is the 2st pthread,pid is %d;tid2=%lu\n",getpid(),pthread_self()); sleep(1); } } int main() { int i=0, ret=0; pthread_t tid1,tid2; printf("main creat thread1\n"); ret = pthread_create(&tid1, NULL, (void*)myThread1, NULL); if (ret) { perror("Create pthread1 error:\n"); return 1; } printf("main creat thread2\n"); ret = pthread_create(&tid2, NULL,(void*) myThread2, NULL); if (ret) { perror("Create pthread2 error:"); return 1; } a++; printf("pthread main : a=%d ",a); printf("This is main pthread,process id is %d;tid=%lu\n",getpid(),pthread_self()); pthread_join(tid1, NULL); printf("tid1 end \n"); pthread_join(tid2, NULL); printf("thread1&thread2 end, a=%d\n",a); return 0; }
相关文章推荐
- 构建centos 5.2系统源码树
- Centos7下安装Chrome浏览器
- linux sed awk
- Linux进程管理命令
- linux守护进程
- Linux系统下给VMWare安装Tools
- linux系统简单搭建iSCSI
- linux进程通信--信号量
- linux进程通信--消息队列
- linux进程通信--共享内存
- CentOS 7系统挂载NTFS分区的移动硬盘(转载及体验 CentOS6.5系统挂载NTFS分区的移动硬盘)
- Linux服务之DNS(bind)
- Zookeeper linux下使用
- 偏执的我从Linux到Windows的感受
- Linux:目录&文件基本操作
- Set Up VTune Amplifier(windows) 2015 for Remote (linux)Analysis
- CentOS 安装远程桌面工具 xrdp 0.6.1
- Centos 7.1 最小安装+更新阿里源+Xfce桌面环境
- Linux系统启动流程
- 常用的Linux命令