在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;
}
以上是兩種常見的線程之間通信的方式,具體使用哪種方式取決于具體的需求和場景。