Linux C++多线程注意事项
在Linux上开发C++多线程程序,可以使用 pthread_t或标准的 std::thread来进行创建。pthread_t是Linux 提供的底层接口,便于对线程进行更加精细的控制。
pthread_t 创建线程的主要流程如下:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/stat.h>
#include <string.h>
// 线程设置
struct sched_param param; //线程调度参数
pthread_attr_t attr; // 线程属性
pthread_t taskThread; // 具体线程
cpu_set_t cpuSet; // CPU亲和性参数
int ret;
ret = pthread_attr_init(&attr);
if (ret)
{
printf("init pthread attributes failed\n");
return ret;
}
// 设置栈空间大小
size_t stack_size = 8 * 1024 * 1024; // 8MB 栈空间 (old: PTHREAD_STACK_MIN)
ret = pthread_attr_setstacksize(&attr, stack_size);
if (ret)
{
printf("pthread attr setstacksize failed\n");
return ret;
}
// 设置线程调度策略
ret = pthread_attr_setschedpolicy(&attr, SCHED_FIFO);
if (ret)
{
printf("pthread setschedpolicy failed\n");
return ret;
}
param.sched_priority = 99; // 设置调度的优先级
ret = pthread_attr_setschedparam(&attr, ¶m);
if (ret)
{
printf("pthread setschedparam failed\n");
return ret;
}
ret = pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);
if (ret)
{
printf("pthread setinheritsched failed\n");
return ret;
}
// 设置CPU的亲和性
CPU_ZERO(&cpuSet);
CPU_SET(cpuIndex, &cpuSet);
ret = pthread_attr_setaffinity_np(&attr, sizeof(cpu_set_t), &cpuSet);
if (ret)
{
printf("---> set thread to cpu0 failed\n");
}
else
{
printf("set thead on cpu0 successful.\n");
}
// 创建任务线程
ret = pthread_create(&taskThread, &attr, task_simulation, nullptr);
if (ret)
{
printf("create task thread failed\n");
return ret;
}
//pthread_join(taskThread, nullptr);
pthread_detach(taskThread);
printf("Create thread successful\n");
注意事项:
- 设置栈空间的大小,一般是
8M,最小为PTHREAD_STACK_MIN16k 。如果设置太小,爆栈会导致段错误。在调用时,可能会由于栈空间溢出导致段错误,内存空间被破坏,无法进入对应的调用函数。 - 线程创建之后:
pthread_join(taskThread, nullptr);会阻塞在主线程的这个位置,直到子线程执行结束,才会继续执行后面的内容,如最后面的printf,这是一种阻塞主线程的方式。pthread_detach(taskThread);:为非阻塞的方式,此时不会阻塞主线程,子线程在执行的同时,pthread_detach后面的代码会继续执行不受影响。
浙公网安备 33010602011771号