C/C++开启线程
1 创建线程函数介绍
C/C++开启线程使用 int pthread_create(thread, attr, start_routine, arg)
函数
参数讲解
thread
需要传入一个 pthread_t
变量的地址,比如 pthread mythread;
attr
设置线程的属性,默认为 NULL
start_routine
线程执行函数的指针,比如 void * myThread(void * arg)
arg
执行函数的参数,只能传入一个参数,如果有多个参数则需要用结构体或者对象进行包装
2 执行流程
3 代码示例
#include <iostream>
#include <pthread.h>
#include <unistd.h>
/**
* 定义线程任务实现
* 传入线程编号
*/
void * myThread(void * arg)
{
std::cout << "start my task !!!" << std::endl;
for (int i = 0; i < 5; i++)
{
std::cout << "thread is working " << std::endl;
sleep(1);
}
return 0;
}
int main()
{
pthread_t pthread;
int result = pthread_create(&pthread, NULL, myThread, NULL);
std::cout << "start my thread, result is " << result << std::endl;
// 这一句如果删除的话,主线程在开启子线程后就结束了,因此会无法看拿到子线程执行过程
pthread_join(pthread, NULL);
return 0;
}
4 函数讲解
sleep
需要使用 unistd.h
头文件,用于执行线程休眠,单位为1s
pthread.h
多线程头文件,包含管理线程的所有函数
编译参数
因为加入了多线程,所以在编译时需要加上参数 -pthread
pthread_join
阻塞等待线程执行结束,获取线程执行状态
cmake增加配置如下:
set(CMAKE_CXX_FLAGS "${CAMKE_CXX_FLAGS} -std=c++11 -pthread")