# 查看当前线程限制
cat /proc/sys/kernel/threads-max
# 临时增加最大线程数(根据系统内存调整)
sudo sysctl -w kernel.threads-max=65536
# 永久生效,在/etc/sysctl.conf中添加
kernel.threads-max = 65536
# 查看当前用户限制
ulimit -a
# 临时修改(会话有效)
ulimit -u 10000 # 最大用户进程数
ulimit -s unlimited # 栈大小
# 永久修改,编辑/etc/security/limits.conf
* soft nproc 10000
* hard nproc 20000
* soft stack unlimited
* hard stack unlimited
# 基于Debian/Ubuntu
sudo apt-get install build-essential gdb glibc-doc libpthread-stubs0-dev
# 基于RHEL/CentOS
sudo yum groupinstall "Development Tools"
sudo yum install glibc-devel gdb
使用gcc编译多线程程序时,需要链接pthread库:
gcc -o my_program my_program.c -lpthread -Wall
#include <pthread.h>
void* thread_function(void* arg) {
// 线程执行的代码
return NULL;
}
int main() {
pthread_t thread_id;
pthread_create(&thread_id, NULL, thread_function, NULL);
pthread_join(thread_id, NULL);
return 0;
}
# 编译时需要-fopenmp选项
gcc -fopenmp -o omp_program omp_program.c
示例代码:
#include <omp.h>
#include <stdio.h>
int main() {
#pragma omp parallel
{
printf("Hello from thread %d\n", omp_get_thread_num());
}
return 0;
}
gdb ./my_program
(gdb) break main
(gdb) run
(gdb) info threads # 查看所有线程
(gdb) thread 2 # 切换到线程2
(gdb) bt # 查看当前线程调用栈
valgrind --tool=helgrind ./my_program # 检测数据竞争
valgrind --tool=drd ./my_program # 检测线程错误
# 记录性能数据
sudo perf record -g ./my_program
# 查看报告
perf report
top -H # 查看线程级别的CPU使用
ps -eLf | grep my_prog # 查看特定程序的线程
#include <sched.h>
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
CPU_SET(0, &cpuset); // 绑定到CPU 0
pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpuset);
struct sched_param param;
param.sched_priority = 99;
pthread_setschedparam(pthread_self(), SCHED_FIFO, ¶m);
注意:需要root权限或适当的能力(capability)设置。
线程创建失败:
ulimit -u
限制性能不佳:
perf
分析热点死锁问题:
helgrind
检测段错误:
gdb
和valgrind
检查内存访问通过以上配置和工具,您可以在Linux系统上高效地进行多线程编程开发。