温馨提示×

pthread_create创建的线程如何共享数据

小樊
129
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