pthreads
是一个用于实现多线程的库,它提供了各种同步原语,如互斥锁(mutex)、条件变量(condition variable)和信号量(semaphore),以帮助在线程之间进行通信和同步
#include <pthread.h>
#include <stdio.h>
pthread_mutex_t lock;
int shared_data = 0;
void* thread_func(void* arg) {
pthread_mutex_lock(&lock);
shared_data++;
printf("Shared data: %d\n", shared_data);
pthread_mutex_unlock(&lock);
return NULL;
}
int main() {
pthread_t threads[5];
pthread_mutex_init(&lock, NULL);
for (int i = 0; i < 5; i++) {
pthread_create(&threads[i], NULL, thread_func, NULL);
}
for (int i = 0; i < 5; i++) {
pthread_join(threads[i], NULL);
}
pthread_mutex_destroy(&lock);
return 0;
}
#include <pthread.h>
#include <stdio.h>
pthread_mutex_t lock;
pthread_cond_t cond;
int shared_data = 0;
void* producer(void* arg) {
pthread_mutex_lock(&lock);
shared_data++;
printf("Produced data: %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("Consumed data: %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_mutex_destroy(&lock);
pthread_cond_destroy(&cond);
return 0;
}
#include <pthread.h>
#include <stdio.h>
#include <semaphore.h>
sem_t semaphore;
int shared_data = 0;
void* producer(void* arg) {
sem_wait(&semaphore);
shared_data++;
printf("Produced data: %d\n", shared_data);
sem_post(&semaphore);
return NULL;
}
void* consumer(void* arg) {
sem_wait(&semaphore);
shared_data--;
printf("Consumed data: %d\n", shared_data);
sem_post(&semaphore);
return NULL;
}
int main() {
pthread_t threads[5];
sem_init(&semaphore, 0, 1); // Initialize semaphore with value 1
for (int i = 0; i < 5; i++) {
pthread_create(&threads[i], NULL, producer, NULL);
pthread_create(&threads[i + 5], NULL, consumer, NULL);
}
for (int i = 0; i < 10; i++) {
pthread_join(threads[i], NULL);
}
sem_destroy(&semaphore);
return 0;
}
这些示例展示了如何使用 pthreads
库中的互斥锁、条件变量和信号量来实现线程通信。在实际应用中,你可能需要根据具体需求选择合适的同步原语和策略。