Linux下的多线程使用的库是pthread,是一个准守POSIX接口的函数库。
Linux下多线程编程对函数定义原型有要求,必须是void *函数名(void *参数名),或者void 函数名(void);
主要创建函数是:
pthread_create
参数:
参数 | 描述 |
---|---|
thread | 指向线程标识符指针。 |
attr | 一个不透明的属性对象,可以被用来设置线程属性。您可以指定线程属性对象,也可以使用默认值 NULL。 |
start_routine | 线程运行函数起始地址,一旦线程被创建就会执行。 |
arg | 运行函数的参数。它必须通过把引用作为指针强制转换为 void 类型进行传递。如果没有传递参数,则使用 NULL。 |
返回值
创建线程成功时,函数返回 0,若返回值不为 0 则说明创建线程失败。
终止线程函数:
pthread_exit
pthread_exit是只能被线程调用,不能用来结束其它线程,如果被main函数调用,则会等待其它线程结束,才会结束main函数
参数 | 描述 |
---|---|
retval | 当结束时,这个参数可以被pthread_join函数获取 |
线程和进程的堆栈是共享的,即便线程调用这个函数结束了,本身所使用的资源是不会结束的,线程不像函数受函数调用保护,会自动清栈,而线程结束了,申请的变量,或者使用的资源都不会被释放
回收函数:
pthread_join
此函数用来等待一个线程结束,并释放此线程的所有资源,并把此线程调用pthread_exit时传递的参数获取到
参数:
参数 | 描述 |
---|---|
thread | 指向线程标识符指针。 |
etval | 用户定义的指针,用来存储被等待线程的返回值。 |
第二个参数会获取到,要回收线程使用pthread_exit的第一个参数对象
头文件:
#include <pthread.h>
实战
1.创建一个简单的线程
#include <stdio.h>
#include <pthread.h>
// 线程的运行函数
void* say_hello(void* args)
{
printf("hello word");
return 0;
}
int main()
{
// 定义线程的 id 变量
pthread_t tids;
int ret = pthread_create(&tids, NULL, say_hello, NULL);
if (ret != 0)
{
printf("线程创建失败");
}
}
//等待线程执行结束
pthread_exit(NULL);
}
编译时要加“-lpthread ”
gcc test.c -lpthread
2. 回收线程
刚刚的demo,因为执行完就会退出程序,所以不需要回收,但是如果线程结束,程序不会退出,就会造成资源浪费,所以改进demo,使用pthread_join回收一下
#include <stdio.h>
#include <pthread.h>
// 线程的运行函数
void* say_hello(void* args)
{
for(int i = 0;i<1000;++i){
printf("hello word");
}
}
int main()
{
// 定义线程的 id 变量
pthread_t tids;
int ret = pthread_create(&tids, NULL, say_hello, NULL);
if (ret != 0)
{
printf("线程创建失败");
}
}
pthread_join(tids,NULL); //阻塞方式
}