插件窝 干货文章 linux线程怎么用

linux线程怎么用

线程 pthread thread attr 694    来源:    2025-04-06

Linux 线程使用指南

在 Linux 系统中,线程是轻量级的进程,共享相同的地址空间。以下是 Linux 线程编程的基本方法:

1. POSIX 线程 (pthread)

Linux 主要使用 POSIX 线程标准 (pthread) 来实现多线程编程。

基本步骤

  1. 包含头文件

    #include <pthread.h>
    
  2. 创建线程

    int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                     void *(*start_routine) (void *), void *arg);
    
  3. 等待线程结束

    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;
}

2. 线程同步

互斥锁 (Mutex)

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

// 加锁
pthread_mutex_lock(&mutex);

// 临界区代码

// 解锁
pthread_mutex_unlock(&mutex);

条件变量 (Condition Variables)

pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

// 等待条件
pthread_cond_wait(&cond, &mutex);

// 通知等待的线程
pthread_cond_signal(&cond);  // 通知一个线程
pthread_cond_broadcast(&cond);  // 通知所有线程

3. 线程属性

可以设置线程属性来控制线程行为:

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);

4. 线程局部存储

// 定义线程局部变量
static __thread int tls_var;

void *thread_func(void *arg) {
    tls_var = 42;  // 每个线程有自己的副本
    // ...
}

5. 编译

使用 gcc 编译时需要链接 pthread 库:

gcc program.c -o program -lpthread

6. 查看线程信息

在 Linux 终端中可以使用以下命令查看线程信息:

ps -eLf  # 查看所有线程
top -H    # 以线程模式查看进程

注意事项

  1. 线程间共享全局变量,但需要同步访问
  2. 避免死锁(多个锁的获取顺序要一致)
  3. 考虑线程安全(避免使用非线程安全的函数)
  4. 合理使用线程局部存储减少同步需求

希望这个指南对您有所帮助!如需更详细的信息,可以参考 man pthreads 或相关编程书籍。