linux多线程学习(二)——线程的创建和退出
来源:互联网 发布:单身狗图片 知乎 编辑:程序博客网 时间:2024/06/05 08:27
创建线程实际上就是确定调用该线程函数的入口点,这里通常使用的函数是pthread_create。在线程创建之后,就开始运行相关的线程函数。在该函数运行结束,线程也会随着退出。这是其中退出线程的一种方法,另外一种退出线程的方法就是调用pthread_exit()函数接口,这是结束函数的主动行为。在这里要注意的是,在使用线程函数时,不要轻易调用exit()函数,因为这样会使整个进程退出,往往一个进程包含着多个线程,所以调用了exit()之后,所有该进程中的线程都会被结束掉。因此,在线程中,利用pthread_exit来替代进程中的exit。
由于一个进程中的数据段是共享的,因此通常在线程退出之后,退出线程所占的资源并不会随着线程的结束而得到释放。正如进程之间可以调用wait()函数来同步中指并释放资源一样,线程之间也有类似的机制,那就是pthread_join函数.pthread_join可以将当前线程挂起,等待线程的结束,这个函数是一个阻塞函数,调用它的函数将一直等待到被等待的线程结束为止,当函数返回时,被等待函数的资源就会被释放。
1、函数语法简述。
pthread_create
头文件: pthread.h
函数原型: int pthread_create (pthread_t* thread, pthread_attr_t* attr,
void* (start_routine)(void*), void* arg);
函数传入值: thread: 线程标识符
attr: 线程属性设置
start_routine:线程函数入口
arg:传递给线程函数的参数
返回值: 0: 成功
-1: 失败
pthread_exit
头文件: pthread.h
函数原型: void pthread_exit (void* retval);
函数传入值:retval:pthread_exit()调用者线程的返回值,可又其他函数如pthread_join来检索获取。
phread_join
头文件: pthread.h
函数原型: int pthread_join (pthread_t* thread, void** thread_return);
函数传入值:thread:等待线程的标识符。
thread_return:用户定义的指针,用来存储被等待线程的返回值(不为NULL值);
函数返回值:成功: 0
失败:-1
2、函数举例实现。
- #include <stdlib.h>
- #include <stdio.h>
- #include <pthread.h>
- #include <errno.h>
- static void* pthread_func_1 (void*);
- static void* pthread_func_2 (void*);
- int main (int argc, char** argv)
- {
- pthread_t pt_1 = 0;
- pthread_t pt_2 = 0;
- int ret = 0;
- ret = pthread_create (&pt_1, NULL, pthread_func_1, NULL);
- if (ret != 0)
- {
- perror ("pthread_1_create");
- }
- ret = pthread_create (&pt_2, NULL, pthread_func_2, NULL);
- if (ret != 0)
- {
- perror ("pthread_2_create");
- }
- pthread_join (pt_1, NULL);
- pthread_join (pt_2, NULL);
- return 0;
- }
- static void* pthread_func_1 (void* data)
- {
- int i = 0;
- for (; i < 6; i++)
- {
- printf ("This is pthread1!/n");
- if (i == 2)
- {
- pthread_exit (0);
- }
- sleep (1);
- }
- return NULL;
- }
- static void* pthread_func_2 (void* data)
- {
- int i = 0;
- for (; i < 3; i++)
- {
- printf ("This is pthread2!/n");
- }
- pthread_exit (0);
- return NULL;
- }
在上面的例子中只是简单的创建了线程、主动退出线程和挂起线程。在下一篇文章中,将讲述线程线的属性及其设定。
~~END~~
- linux多线程学习(二)—线程的创建和退出
- linux多线程学习(二)——线程的创建和退出
- linux多线程学习(二)——线程的创建和退出
- linux多线程学习(二)——线程的创建和退出
- linux多线程学习(二)——线程的创建和退出
- linux多线程学习(二)——线程的创建和退出
- linux多线程学习(二)——线程的创建和退出
- linux多线程学习(二)——线程的创建和退出
- linux多线程学习(二)——线程的创建和退出
- Linux--多线程之线程的创建和退出
- linux线程的创建和退出(二)
- java多线程学习(二)——线程的创建
- Linux多线程基础学习(二)创建新的线程
- 多线程编程(2): 线程的创建、启动、挂起和退出
- Windows平台的线程——创建和退出
- 线程的创建和退出
- 线程的创建和退出
- 《linux下线程的创建,同步和退出》
- python 迭代器与生成器
- 谷歌- PostMAN的下载和基本使用方法?
- VC单选按钮控件(Radio Button)用法
- Codeforces Round #341 (Div. 2) E. Wet Shark and Blocks(矩阵优化DP)
- 深夜发个小技术贴
- linux多线程学习(二)——线程的创建和退出
- POJ 3268 Silver Cow Party(多源最短路的转化)
- 欢迎使用CSDN-markdown编辑器
- 在开源龙芯1c开发板上用opencv检测图片中网球并输出圆心坐标和半径
- 2016 1 15 关于WebView开发----padding
- POJ 1789 Truck History(最小生成树)
- Spring配置文件中属性值不能提示的解决办法(eclipse添加xsd文件)
- TCP打洞
- 1月11号 自定义ScrollView上拉加载的两种方式