在Linux系统中,线程的创建主要通过以下两种方式实现:
需要包含头文件 <pthread.h>
,编译时添加 -lpthread
选项。
示例代码:
#include <pthread.h>
#include <stdio.h>
void* thread_function(void* arg) {
printf("Thread ID: %lu\n", (unsigned long)pthread_self());
return NULL;
}
int main() {
pthread_t thread_id;
int ret = pthread_create(&thread_id, NULL, thread_function, NULL);
if (ret != 0) {
perror("pthread_create failed");
return 1;
}
pthread_join(thread_id, NULL); // 等待线程结束
return 0;
}
关键函数:
pthread_create()
: 创建线程,参数包括线程ID、属性、线程函数和参数。pthread_join()
: 阻塞等待线程结束。pthread_self()
: 获取当前线程ID。
特点:
通常由pthread
库内部调用,普通开发者较少直接使用。
示例代码:
#include <sched.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#define STACK_SIZE 1024 * 1024 // 1MB栈空间
int child_func(void* arg) {
printf("Thread (clone) ID: %d\n", gettid());
return 0;
}
int main() {
char* stack = malloc(STACK_SIZE);
if (stack == NULL) {
perror("malloc failed");
return 1;
}
pid_t pid = clone(child_func, stack + STACK_SIZE,
CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND, NULL);
if (pid == -1) {
perror("clone failed");
free(stack);
return 1;
}
waitpid(pid, NULL, 0); // 等待子线程
free(stack);
return 0;
}
关键参数:
CLONE_VM
: 共享内存空间(线程的核心标志)。CLONE_FS | CLONE_FILES
: 共享文件系统信息和文件描述符。注意:直接使用clone()
需谨慎管理栈空间和资源。
特点:
std::thread
:pthread
):
cpp
#include <thread>
#include <iostream>
void thread_func() { std::cout << "C++ Thread\n"; }
int main() { std::thread t(thread_func); t.join(); }
方式 | 适用场景 | 优点 | 缺点 |
---|---|---|---|
pthread |
通用多线程开发 | 标准化、易用、功能丰富 | 需链接-lpthread |
clone() |
特殊需求或内核开发 | 极细粒度控制 | 复杂、易出错 |
std::thread |
C++项目 | 语法简洁、跨平台 | 仅限C++ |
线程 vs 进程
线程属性设置
pthread_attr_t
设置栈大小、分离状态等:
c
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
错误处理
pthread
函数返回错误码(非errno
),需用strerror(ret)
打印错误信息。根据需求选择合适的线程创建方式,推荐优先使用pthread
库。