在C語言中,使用pthread_create
創建的線程可以通過以下方法共享數據:
#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;
}
#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;
}
_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;
}
請注意,這些方法各有優缺點,具體選擇哪種方法取決于程序的需求和場景。在使用共享數據時,務必注意線程安全和同步問題,以避免數據競爭和不一致的問題。