CMake编译链接线程库
1. 设置链接选项
使用 CMake 编译程序时,需要设置链接选项来链接 pthread 库。
在 CMakeLists.txt 文件中添加链接选项,即在add_executable()下面添加以下代码将 pthread 链接库添加到目标可执行文件中:
target_link_libraries(target_name pthread)
target_name为目标可执行文件的名称。
2. 进行编译
使用make命令进行编译即可。
线程绑定
程序中使用多线程时,通常会将线程指定到某个CPU上运行,这样可以减少竞争,提高程序应用性能。但是linux下和windows的写法不太一样,下面就总结一下在linux下的线程绑定方法。
主要使用pthread_setaffinity_np()函数将线程绑定到指定的CPU,该函数需要传入线程ID和一个CPU集合参数,其中CPU集合参数表示要使用的CPU编号。
具体步骤如下:
1. 添加头文件
#include <pthread.h>
2. 定义线程执行函数
void *thread_func(void *arg)
{
// 线程执行的任务
// ...
}
3. 创建线程
pthread_t thread_id;
pthread_create(&thread_id, NULL, &thread_func, NULL);
4. 设置CPU集合
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
CPU_SET(cpu_id, &cpuset);
5. 线程绑定到指定CPU
pthread_setaffinity_np(thread_id, sizeof(cpuset), &cpuset);
6. 等待子线程执行完毕
pthread_join(thread_id, NULL);
注:上述中cpu_id为绑定的CPU编号,即 0,1,2...
结语
道阻且长,且学且珍惜......
总结不易,点个赞吧(●'◡'●)