在Linux中,使用POSIX線程(pthread)庫進行線程間通信有多種方法。以下是一些常用的線程間通信方式:
pthread_mutex_t
類型的互斥鎖,以及用于操作互斥鎖的函數,如pthread_mutex_lock()
和pthread_mutex_unlock()
。示例:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
pthread_mutex_t lock;
int shared_data = 0;
void* increment(void* arg) {
pthread_mutex_lock(&lock);
shared_data++;
pthread_mutex_unlock(&lock);
return NULL;
}
int main() {
pthread_t thread1, thread2;
pthread_mutex_init(&lock, NULL);
pthread_create(&thread1, NULL, increment, NULL);
pthread_create(&thread2, NULL, increment, NULL);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
printf("Shared data: %d\n", shared_data);
pthread_mutex_destroy(&lock);
return 0;
}
pthread_cond_t
類型的條件變量,以及用于操作條件變量的函數,如pthread_cond_wait()
和pthread_cond_signal()
。示例:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
pthread_mutex_t lock;
pthread_cond_t cond;
int shared_data = 0;
void* producer(void* arg) {
pthread_mutex_lock(&lock);
shared_data++;
printf("Producer: %d\n", shared_data);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&lock);
return NULL;
}
void* consumer(void* arg) {
pthread_mutex_lock(&lock);
while (shared_data == 0) {
pthread_cond_wait(&cond, &lock);
}
shared_data--;
printf("Consumer: %d\n", shared_data);
pthread_mutex_unlock(&lock);
return NULL;
}
int main() {
pthread_t producer_thread, consumer_thread;
pthread_mutex_init(&lock, NULL);
pthread_cond_init(&cond, NULL);
pthread_create(&producer_thread, NULL, producer, NULL);
pthread_create(&consumer_thread, NULL, consumer, NULL);
pthread_join(producer_thread, NULL);
pthread_join(consumer_thread, NULL);
pthread_cond_destroy(&cond);
pthread_mutex_destroy(&lock);
return 0;
}
信號量(Semaphore):信號量是一種計數器,用于控制對共享資源的訪問。pthread提供了sem_t
類型的信號量,以及用于操作信號量的函數,如sem_wait()
和sem_post()
。
消息隊列(Message Queue):消息隊列是一種通信方式,允許線程發送和接收消息。Linux提供了System V消息隊列,可以通過msgget()
、msgsnd()
和msgrcv()
等函數進行操作。
這些方法可以根據不同的場景和需求進行選擇。在實際應用中,可能需要結合多種方法來實現復雜的線程間通信。