在 Linux 系统中,线程是轻量级的进程,共享相同的地址空间。以下是 Linux 线程编程的基本方法:
Linux 主要使用 POSIX 线程标准 (pthread) 来实现多线程编程。
包含头文件
#include <pthread.h>
创建线程
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg);
等待线程结束
int pthread_join(pthread_t thread, void **retval);
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
void *thread_function(void *arg) {
int *value = (int *)arg;
printf("Thread received value: %d\n", *value);
return NULL;
}
int main() {
pthread_t thread_id;
int value = 42;
// 创建线程
if (pthread_create(&thread_id, NULL, thread_function, &value) != 0) {
perror("pthread_create failed");
exit(EXIT_FAILURE);
}
// 等待线程结束
if (pthread_join(thread_id, NULL) != 0) {
perror("pthread_join failed");
exit(EXIT_FAILURE);
}
printf("Main thread exiting\n");
return 0;
}
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
// 加锁
pthread_mutex_lock(&mutex);
// 临界区代码
// 解锁
pthread_mutex_unlock(&mutex);
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
// 等待条件
pthread_cond_wait(&cond, &mutex);
// 通知等待的线程
pthread_cond_signal(&cond); // 通知一个线程
pthread_cond_broadcast(&cond); // 通知所有线程
可以设置线程属性来控制线程行为:
pthread_attr_t attr;
pthread_attr_init(&attr);
// 设置线程为分离状态(不需要join)
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
// 创建线程时使用属性
pthread_create(&thread_id, &attr, thread_function, NULL);
// 销毁属性对象
pthread_attr_destroy(&attr);
// 定义线程局部变量
static __thread int tls_var;
void *thread_func(void *arg) {
tls_var = 42; // 每个线程有自己的副本
// ...
}
使用 gcc 编译时需要链接 pthread 库:
gcc program.c -o program -lpthread
在 Linux 终端中可以使用以下命令查看线程信息:
ps -eLf # 查看所有线程
top -H # 以线程模式查看进程
希望这个指南对您有所帮助!如需更详细的信息,可以参考 man pthreads
或相关编程书籍。