C语言中线程怎么创建C语言pthread库的基本使用教程

来源:这里教程网 时间:2026-02-21 17:05:57 作者:

c语言中创建线程主要使用pthread库,通过pthread_create函数指定线程执行的函数。1. 首先包含头文件pthread.h;2. 使用pthread_create函数创建线程,传入线程id、属性(通常为null)、线程执行函数及其参数;3. 线程执行完毕后可通过pthread_join获取返回值;4. 编译时需链接pthread库,使用命令gcc -pthread。此外,pthread库还提供pthread_mutex_lock/unlock用于互斥访问共享资源,以及pthread_cond_wait/signal用于线程间条件同步。为避免死锁,应遵循一致的锁获取顺序、使用超时机制或采用锁层次结构。

C语言中线程怎么创建C语言pthread库的基本使用教程

C语言中创建线程,主要依赖pthread库。它并非C语言标准库的一部分,但在POSIX兼容的系统(比如Linux、macOS)上广泛可用。简单来说,就是用

pthread_create
函数,给它指定一个函数作为线程的入口,然后它就会帮你创建一个新的线程来执行这个函数。

C语言中线程怎么创建C语言pthread库的基本使用教程

解决方案

C语言中线程怎么创建C语言pthread库的基本使用教程

要使用pthread库,首先得包含头文件

pthread.h
。然后,最核心的函数是
pthread_create
。这个函数原型是这样的:

立即学习“C语言免费学习笔记(深入)”;

C语言中线程怎么创建C语言pthread库的基本使用教程
#include <pthread.h>
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                   void *(*start_routine) (void *), void *arg);
thread
: 指向
pthread_t
类型变量的指针,用于存储新创建线程的ID。
attr
: 线程属性,通常设为
NULL
使用默认属性。
start_routine
: 函数指针,指向线程要执行的函数。这个函数必须接受一个
void*
类型的参数,并返回一个
void*
类型的值。
arg
: 传递给
start_routine
函数的参数。

一个简单的例子:

#include <stdio.h>
#include <pthread.h>
void *thread_function(void *arg) {
    int thread_id = *(int*)arg;
    printf("线程 %d 正在执行\n", thread_id);
    pthread_exit(NULL); // 线程退出
}
int main() {
    pthread_t thread1, thread2;
    int id1 = 1, id2 = 2;
    if (pthread_create(&thread1, NULL, thread_function, &id1) != 0) {
        perror("创建线程1失败");
        return 1;
    }
    if (pthread_create(&thread2, NULL, thread_function, &id2) != 0) {
        perror("创建线程2失败");
        return 1;
    }
    pthread_join(thread1, NULL); // 等待线程1结束
    pthread_join(thread2, NULL); // 等待线程2结束
    printf("主线程结束\n");
    return 0;
}

编译时需要链接pthread库:

gcc your_file.c -o your_program -pthread

pthread库中还有其他重要的函数:

pthread_join
: 等待指定的线程结束。如果线程已经结束,
pthread_join
会立即返回。
pthread_exit
: 线程退出。
pthread_mutex_lock
,
pthread_mutex_unlock
: 互斥锁,用于线程同步,防止多个线程同时访问共享资源。
pthread_cond_wait
,
pthread_cond_signal
: 条件变量,也用于线程同步。

如何处理线程中的返回值?

pthread_join
函数可以用来获取线程的返回值。
pthread_join
的第二个参数是一个
void**
类型的指针,指向一个用于存储线程返回值的指针。如果线程通过
pthread_exit
返回一个值,或者通过
return
语句返回一个值(在线程函数中),那么这个值就可以通过
pthread_join
获取。

例如:

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
void *thread_function(void *arg) {
    int *result = malloc(sizeof(int));
    *result = *(int*)arg * 2;
    pthread_exit(result); // 线程退出,返回结果
}
int main() {
    pthread_t thread;
    int input = 10;
    void *thread_result;
    if (pthread_create(&thread, NULL, thread_function, &input) != 0) {
        perror("创建线程失败");
        return 1;
    }
    pthread_join(thread, &thread_result); // 等待线程结束,并获取返回值
    if (thread_result != NULL) {
        int result = *(int*)thread_result;
        printf("线程的返回值为: %d\n", result);
        free(thread_result); // 释放内存
    }
    printf("主线程结束\n");
    return 0;
}

注意,线程返回的内存需要手动释放,否则会造成内存泄漏。

线程同步:互斥锁和条件变量

线程同步是多线程编程中一个非常重要的话题。当多个线程需要访问共享资源时,如果没有适当的同步机制,可能会导致数据竞争和不确定的行为。pthread库提供了互斥锁(mutex)和条件变量(condition variable)来实现线程同步。

互斥锁

互斥锁用于保护共享资源,确保同一时刻只有一个线程可以访问它。

#include <stdio.h>
#include <pthread.h>
pthread_mutex_t mutex; // 互斥锁变量
int shared_data = 0;
void *thread_function(void *arg) {
    for (int i = 0; i < 1000000; i++) {
        pthread_mutex_lock(&mutex); // 加锁
        shared_data++;
        pthread_mutex_unlock(&mutex); // 解锁
    }
    pthread_exit(NULL);
}
int main() {
    pthread_t thread1, thread2;
    pthread_mutex_init(&mutex, NULL); // 初始化互斥锁
    pthread_create(&thread1, NULL, thread_function, NULL);
    pthread_create(&thread2, NULL, thread_function, NULL);
    pthread_join(thread1, NULL);
    pthread_join(thread2, NULL);
    printf("共享数据的值: %d\n", shared_data);
    pthread_mutex_destroy(&mutex); // 销毁互斥锁
    return 0;
}

条件变量

条件变量用于线程间的通信。一个线程可以等待某个条件成立,而另一个线程可以在条件成立时通知等待的线程。

#include <stdio.h>
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t cond;
int data_ready = 0;
void *producer_function(void *arg) {
    pthread_mutex_lock(&mutex);
    // 生产数据...
    data_ready = 1;
    pthread_cond_signal(&cond); // 通知消费者线程
    pthread_mutex_unlock(&mutex);
    pthread_exit(NULL);
}
void *consumer_function(void *arg) {
    pthread_mutex_lock(&mutex);
    while (!data_ready) {
        pthread_cond_wait(&cond, &mutex); // 等待条件成立,并释放锁
    }
    // 消费数据...
    pthread_mutex_unlock(&mutex);
    pthread_exit(NULL);
}
int main() {
    pthread_t producer, consumer;
    pthread_mutex_init(&mutex, NULL);
    pthread_cond_init(&cond, NULL);
    pthread_create(&producer, NULL, producer_function, NULL);
    pthread_create(&consumer, NULL, consumer_function, NULL);
    pthread_join(producer, NULL);
    pthread_join(consumer, NULL);
    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond);
    return 0;
}

如何避免死锁?

死锁是指两个或多个线程互相等待对方释放资源,导致所有线程都无法继续执行的情况。避免死锁的一些常见方法包括:

避免循环等待: 确保线程获取锁的顺序一致。 使用超时机制: 尝试获取锁时设置超时时间,如果超时则放弃,避免无限等待。 使用锁层次结构: 为锁分配优先级,线程必须按照优先级从高到低的顺序获取锁。

例如,如果线程需要同时获取锁A和锁B,可以始终按照相同的顺序获取锁,比如先获取锁A,再获取锁B。 这样可以避免线程1获取锁A等待锁B,而线程2获取锁B等待锁A的情况发生。

相关推荐