在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;
}
以上是两种常见的线程之间通信的方式,具体使用哪种方式取决于具体的需求和场景。