C实现多读者多写着互斥问题
时间: 2024-03-01 11:55:27 浏览: 23
实现多读者多写者互斥问题可以使用读写锁来解决。读写锁在同一时刻只允许一个写者访问共享资源,但允许多个读者在同一时刻访问共享资源。
以下是一个使用读写锁实现多读者多写者互斥的C代码示例:
```c
#include <pthread.h>
pthread_rwlock_t rwlock;
int shared_data;
void* writer(void* arg) {
int data = *(int*)arg;
pthread_rwlock_wrlock(&rwlock);
shared_data = data;
pthread_rwlock_unlock(&rwlock);
return NULL;
}
void* reader(void* arg) {
int* data = (int*)arg;
pthread_rwlock_rdlock(&rwlock);
*data = shared_data;
pthread_rwlock_unlock(&rwlock);
return NULL;
}
int main() {
pthread_t writer_threads[5];
pthread_t reader_threads[5];
int data[5];
int i;
pthread_rwlock_init(&rwlock, NULL);
for (i = 0; i < 5; i++) {
pthread_create(&writer_threads[i], NULL, writer, &i);
pthread_create(&reader_threads[i], NULL, reader, &data[i]);
}
for (i = 0; i < 5; i++) {
pthread_join(writer_threads[i], NULL);
pthread_join(reader_threads[i], NULL);
printf("Data read by reader thread %d: %d\n", i, data[i]);
}
pthread_rwlock_destroy(&rwlock);
return 0;
}
```
在这个示例中,我们创建了5个写者线程和5个读者线程。写者线程将一个整数值写入共享数据中,而读者线程从共享数据中读取一个整数值。在读写时,我们使用 pthread_rwlock_wrlock() 和 pthread_rwlock_rdlock() 函数来获取写锁和读锁。在完成读写操作后,我们使用 pthread_rwlock_unlock() 函数释放锁。最后,我们使用 pthread_rwlock_init() 和 pthread_rwlock_destroy() 函数进行读写锁的初始化和销毁。