linux创建线程
来源:互联网 发布:淘宝雷锋侠的权益 编辑:程序博客网 时间:2024/06/04 01:02
线程:
进程:资源分配的基本单位
线程:系统调度的基本单位
线程创建: pthread_create (&tid 返回子线程ID, 属性,子线程函数入口(函数指针),函数传入参数)
sqrt :-lm --> - link libm.a
pthread:-lpthread -> -link libpthread.a
线程创建时候要注意属性:
优先级 、调度、分离状态(detach? joined?)、栈大小及起始地址,没有特殊要求就设成NULL
系统默认是个join线程,非分离
子线程函数入口 是有返回值void *的, 也可以传入参数,具体的参数类型是第四个参数传入
线程的回收: 只针对的是非分离线程 pthread_join
注意: 1:主线程会先继续执行;
如果主线程没有等待回收或者其它阻塞,主线程结束的时候,整个进程也就结束了
2:如果线程中调用了exit类的函数,会直接退出整个进程;
进程:资源分配的基本单位
线程:系统调度的基本单位
线程创建: 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 runreturn (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;}
0 0
- linux 线程编程:线程创建
- Linux线程-创建
- linux 下创建线程
- LINUX 创建线程例子
- linux 内核线程创建
- linux 创建线程
- Linux创建线程
- Linux创建线程
- linux下创建线程
- linux创建线程
- Linux创建子线程
- Linux线程的创建
- linux内核线程 [创建]
- linux内核创建线程
- Linux 内核线程创建
- Linux 创建线程
- linux 创建内核线程
- Linux线程创建
- while(cin)循环的控制判断
- python自动发送邮件自定义邮件发件人和收件人的显示内容
- 杭电OJ-- 2094 产生冠军
- Android ListView监听上滑、下滑、滑到顶部/底部
- hdu1084代码过程的反省
- linux创建线程
- RabbitMQ > Spring AMQP
- SAP HR
- [Mac] Terminal and Vim theme
- log4j1.2简介
- 面试时被问到了volatile ,找个文章总结一下
- 2015沈阳网络赛 1002(HDU 5451 矩阵快速幂 + 矩阵循环群)
- 『解开人生的迷茫』
- selenium+python的WebDriverWait使用方法