c语言两个线程之间怎么通信

   2025-02-19 3640
核心提示:在C语言中,可以使用以下方法实现两个线程之间的通信:全局变量:两个线程可以共享一个全局变量,并通过对该变量的读写来进行通

在C语言中,可以使用以下方法实现两个线程之间的通信:

全局变量:两个线程可以共享一个全局变量,并通过对该变量的读写来进行通信。需要注意的是,对全局变量的读写需要加锁以避免竞争条件。

示例代码:

#include <stdio.h>#include <pthread.h>int shared_variable = 0;pthread_mutex_t mutex;void* thread1(void* arg) {pthread_mutex_lock(&mutex);shared_variable = 1;  // 修改共享变量pthread_mutex_unlock(&mutex);return NULL;}void* thread2(void* arg) {pthread_mutex_lock(&mutex);printf("Shared variable: %d\n", shared_variable);  // 读取共享变量pthread_mutex_unlock(&mutex);return NULL;}int main() {pthread_t t1, t2;pthread_mutex_init(&mutex, NULL);pthread_create(&t1, NULL, thread1, NULL);pthread_create(&t2, NULL, thread2, NULL);pthread_join(t1, NULL);pthread_join(t2, NULL);pthread_mutex_destroy(&mutex);return 0;}
条件变量:一个线程等待另一个线程发出特定信号后才继续执行。其中,等待线程使用pthread_cond_wait()阻塞自己,发送信号的线程使用pthread_cond_signal()pthread_cond_broadcast()发送信号。

示例代码:

#include <stdio.h>#include <pthread.h>int shared_variable = 0;pthread_mutex_t mutex;pthread_cond_t cond;void* thread1(void* arg) {pthread_mutex_lock(&mutex);shared_variable = 1;  // 修改共享变量pthread_cond_signal(&cond);  // 发送信号给等待的线程pthread_mutex_unlock(&mutex);return NULL;}void* thread2(void* arg) {pthread_mutex_lock(&mutex);while (shared_variable == 0) {pthread_cond_wait(&cond, &mutex);  // 等待信号}printf("Shared variable: %d\n", shared_variable);  // 读取共享变量pthread_mutex_unlock(&mutex);return NULL;}int main() {pthread_t t1, t2;pthread_mutex_init(&mutex, NULL);pthread_cond_init(&cond, NULL);pthread_create(&t1, NULL, thread1, NULL);pthread_create(&t2, NULL, thread2, NULL);pthread_join(t1, NULL);pthread_join(t2, NULL);pthread_mutex_destroy(&mutex);pthread_cond_destroy(&cond);return 0;}

以上是两种常见的线程之间通信的方式,具体使用哪种方式取决于具体的需求和场景。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言