溫馨提示×

pthread_create創建的線程如何共享數據

小樊
118
2024-12-28 23:21:16
欄目: 編程語言

在C語言中,使用pthread_create創建的線程可以通過以下方法共享數據:

  1. 使用全局變量:將需要共享的數據定義為全局變量,這樣所有線程都可以訪問和修改這些變量。但是,這種方法可能導致數據競爭和不一致的問題,因此需要使用互斥鎖(mutex)或其他同步機制來確保線程安全。
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

// 定義全局變量
int shared_data = 0;
pthread_mutex_t lock;

// 線程函數
void *thread_func(void *arg) {
    for (int i = 0; i < 10; i++) {
        // 獲取鎖
        pthread_mutex_lock(&lock);
        shared_data++;
        printf("Thread %ld, shared_data: %d\n", (long)arg, shared_data);
        // 釋放鎖
        pthread_mutex_unlock(&lock);
    }
    return NULL;
}

int main() {
    pthread_t threads[5];
    int num_threads = 5;

    // 初始化互斥鎖
    pthread_mutex_init(&lock, NULL);

    // 創建線程
    for (int i = 0; i < num_threads; i++) {
        pthread_create(&threads[i], NULL, thread_func, (void *)(long)i);
    }

    // 等待線程結束
    for (int i = 0; i < num_threads; i++) {
        pthread_join(threads[i], NULL);
    }

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

    return 0;
}
  1. 使用靜態變量:如果函數是線程安全的,可以將需要共享的數據定義為靜態變量。這樣,所有調用該函數的線程都將訪問和修改相同的變量。但是,這種方法僅適用于函數范圍內的共享數據。
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

// 定義靜態變量
static int shared_data = 0;

// 線程函數
void *thread_func(void *arg) {
    for (int i = 0; i < 10; i++) {
        shared_data++;
        printf("Thread %ld, shared_data: %d\n", (long)arg, shared_data);
    }
    return NULL;
}

int main() {
    pthread_t threads[5];
    int num_threads = 5;

    // 創建線程
    for (int i = 0; i < num_threads; i++) {
        pthread_create(&threads[i], NULL, thread_func, (void *)(long)i);
    }

    // 等待線程結束
    for (int i = 0; i < num_threads; i++) {
        pthread_join(threads[i], NULL);
    }

    return 0;
}
  1. 使用線程局部存儲(Thread Local Storage,TLS):如果每個線程都需要有自己的數據副本,可以使用TLS。這樣,每個線程都將擁有自己的數據實例,而不是共享相同的數據。在C11標準中,可以使用_Thread_local關鍵字來定義線程局部變量。
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

// 定義線程局部變量
__thread int shared_data = 0;

// 線程函數
void *thread_func(void *arg) {
    for (int i = 0; i < 10; i++) {
        shared_data++;
        printf("Thread %ld, shared_data: %d\n", (long)arg, shared_data);
    }
    return NULL;
}

int main() {
    pthread_t threads[5];
    int num_threads = 5;

    // 創建線程
    for (int i = 0; i < num_threads; i++) {
        pthread_create(&threads[i], NULL, thread_func, (void *)(long)i);
    }

    // 等待線程結束
    for (int i = 0; i < num_threads; i++) {
        pthread_join(threads[i], NULL);
    }

    return 0;
}

請注意,這些方法各有優缺點,具體選擇哪種方法取決于程序的需求和場景。在使用共享數據時,務必注意線程安全和同步問題,以避免數據競爭和不一致的問題。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女