pthread多线程的使用

pthread 是 POSIX threads 的简称,POSIX 线程是一个 POSIX 标准线程。

该标准定义内部API创建和操作线程。

1、创建

通过 pthread_create() 创建线程

int pthread_create( pthread_t * thread, const pthread_attr_t, void * (*start_function) ( void *), void * args )

2、参数

2.1、pthread_create 参数理解

第一个参数:线程ID指针,本质上是线程ID 的写入地址

第二个参数:线程属性参数

第三个参数:线程运行函数func的地址

第四个参数:线程运行函数func的参数

进一步说明:

(1)第一个参数是pthread_t类型指针,宏pthread_t 原型是 unsigned int,用于存储线程ID

(2)第三个参数 void * (*start_function) ( void *) 含义是指向返回值为 void * ,参数类型为 void * 的函数指针

2.2、pthread_create 返回值理解

pthread_create 返回一个int值,线程创建成功时返回0;其他值都表示创建线程发生错误。

这里容易误解为返回线程ID,其实不是。

3、编译

编译的时候需要带有 -pthread

举例:g++ -pthread -o cpp_multi cpp_multi.cpp

4、实验

pthread_t* p_arr = (pthread_t* ) malloc(THREAD_NUM * sizeof(pthread_t));

pthread多线程的使用_第1张图片
main
pthread多线程的使用_第2张图片
thread_func
pthread多线程的使用_第3张图片
result

你可能感兴趣的:(pthread多线程的使用)