c語言多線程怎么訪問全局變量

小億
204
2024-01-30 15:44:35
欄目: 編程語言

在C語言中,多線程訪問全局變量需要注意線程同步問題,以避免出現(xiàn)數(shù)據(jù)競(jìng)爭(zhēng)和不確定的結(jié)果。以下是幾種常見的方法:

  1. 使用互斥鎖(mutex):在訪問全局變量之前,線程先獲取互斥鎖,訪問結(jié)束后再釋放互斥鎖。這樣可以確保同一時(shí)間只有一個(gè)線程能夠訪問全局變量。
#include <pthread.h>

int global_variable;
pthread_mutex_t mutex;

void* thread_function(void* arg) {
    // 獲取互斥鎖
    pthread_mutex_lock(&mutex);

    // 訪問全局變量
    global_variable++;

    // 釋放互斥鎖
    pthread_mutex_unlock(&mutex);

    return NULL;
}

int main() {
    // 初始化互斥鎖
    pthread_mutex_init(&mutex, NULL);

    // 創(chuàng)建線程
    pthread_t thread;
    pthread_create(&thread, NULL, thread_function, NULL);

    // 等待線程結(jié)束
    pthread_join(thread, NULL);

    // 銷毀互斥鎖
    pthread_mutex_destroy(&mutex);

    return 0;
}
  1. 使用信號(hào)量(semaphore):設(shè)置一個(gè)信號(hào)量為1,在訪問全局變量之前,線程先執(zhí)行P操作(等待),訪問結(jié)束后再執(zhí)行V操作(釋放)。
#include <pthread.h>
#include <semaphore.h>

int global_variable;
sem_t sem;

void* thread_function(void* arg) {
    // 等待信號(hào)量
    sem_wait(&sem);

    // 訪問全局變量
    global_variable++;

    // 釋放信號(hào)量
    sem_post(&sem);

    return NULL;
}

int main() {
    // 初始化信號(hào)量
    sem_init(&sem, 0, 1);

    // 創(chuàng)建線程
    pthread_t thread;
    pthread_create(&thread, NULL, thread_function, NULL);

    // 等待線程結(jié)束
    pthread_join(thread, NULL);

    // 銷毀信號(hào)量
    sem_destroy(&sem);

    return 0;
}
  1. 使用條件變量(condition variable):設(shè)置一個(gè)條件變量和一個(gè)互斥鎖,線程通過互斥鎖來保護(hù)對(duì)全局變量的訪問,在訪問之前,線程等待條件變量滿足,訪問結(jié)束后,通過條件變量通知其他等待的線程。
#include <pthread.h>

int global_variable;
pthread_mutex_t mutex;
pthread_cond_t cond;

void* thread_function(void* arg) {
    // 獲取互斥鎖
    pthread_mutex_lock(&mutex);

    // 等待條件變量滿足
    while (global_variable == 0) {
        pthread_cond_wait(&cond, &mutex);
    }

    // 訪問全局變量
    global_variable++;

    // 釋放互斥鎖
    pthread_mutex_unlock(&mutex);

    return NULL;
}

int main() {
    // 初始化互斥鎖和條件變量
    pthread_mutex_init(&mutex, NULL);
    pthread_cond_init(&cond, NULL);

    // 創(chuàng)建線程
    pthread_t thread;
    pthread_create(&thread, NULL, thread_function, NULL);

    // 修改全局變量,并發(fā)送條件變量通知
    pthread_mutex_lock(&mutex);
    global_variable++;
    pthread_cond_signal(&cond);
    pthread_mutex_unlock(&mutex);

    // 等待線程結(jié)束
    pthread_join(thread, NULL);

    // 銷毀互斥鎖和條件變量
    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond);

    return 0;
}

通過以上方法,可以確保多個(gè)線程能夠安全地訪問全局變量,避免數(shù)據(jù)競(jìng)爭(zhēng)和不確定的結(jié)果。

0