Linux 线程
1.线程概念:一个进程内部的一个控制序列
2.特点:一个进程在同一时刻只做一件事情。有了多个控制线程以后,在程序设计时可以把进程设计成在同一时刻能够做不止一件事,每个线程处理各只独立的任务。
3.线程的标识:线程ID用pthread_t数据类型来表示,实现的时候可以用一个结构来代表pthread_t数据类型,所以可以移植的操作系统不能把它作为整数处理。
4.线程的创建:pthread_create
简介:头文件 #include<pthread.h>
函数原型:int pthread_create(pthread_t *restrict tidp,const pthread _attr_t *restrict attr,void *(*start_rtn)(void),void *restrict arg);
返回值:若成功返回0,失败返回错误编码
过程: 当pthread_creat成功返回时, tidp指向的内存单元被设置为新创建线程的线程ID。attr参数用于定制各种不同的线程属性。可以把它设置为NULL,创建默认的线程属性。
新创建的线程从start_rtn函数的地址开始运行,该函数只有一个无类型指针参数arg,如果需要向start_rtn函数传递的参数不止一个,那么需要把这些参数放到一个结构中,然后把这个结构的地址作为arg参数传入。
编译过程(注意):关于进程的编译我们都要加上参数 –lpthread 否则提示找不到函数的错误。
5.线程的终止
函数:pthread_join(获得进程的终止状态)
头文件: #include<pthread.h>
函数原型:int pthread_join(pthread_t thread,void **rval_ptr);
返回值:成功返回0,失败返回错误编号
代码演示线程的创建和退出:
1 #include<pthread.h>
2 #include<stdio.h>
3
4 void* pthread_fun(void *arg)
5 {
6 printf("create a pthread!\n");
7 }
8 int main()
9 {
10 pthread_t tid;
11 pthread_create(&tid,NULL,pthread_fun,NULL);
12
13
14 pthread_join(tid,NULL);
15 return 0;
16 }
结果:create a pthread!