在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; }
请注意,这些方法各有优缺点,具体选择哪种方法取决于程序的需求和场景。在使用共享数据时,务必注意线程安全和同步问题,以避免数据竞争和不一致的问题。