写一个linux系统下的c代码片段,功能为创建两个线程,分别对公共资源进行读写,线程A读取值,线程B写入值,两个线程通过linux读写锁pthread_rwlock_t进行互斥
时间: 2024-09-26 11:12:19 浏览: 32
在Linux系统下,使用C语言编写一个简单的线程示例,我们将创建两个线程,线程A负责读取公共资源,线程B负责写入。这里我们使用`pthread_rwlock_t`(读写锁)来进行互斥访问:
```c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define MAX_VALUE 100
int shared_value = 0;
pthread_rwlock_t read_write_lock;
void *thread_reader(void *arg) {
int i;
pthread_rwlock_rdlock(&read_write_lock);
for (i = 0; i < MAX_VALUE; ++i) {
printf("Thread A reading: %d\n", shared_value);
// 模拟读取操作,实际应用中此处应替换为真实的读操作
sleep(1); // 稳定演示
}
pthread_rwlock_unlock(&read_write_lock);
return NULL;
}
void *thread_writer(void *arg) {
int i;
for (i = 0; i < MAX_VALUE; ++i) {
pthread_rwlock_wrlock(&read_write_lock);
shared_value += 1;
printf("Thread B writing: %d\n", shared_value);
pthread_rwlock_unlock(&read_write_lock);
sleep(1); // 稳定演示
}
return NULL;
}
int main() {
pthread_t reader_thread, writer_thread;
if (pthread_rwlock_init(&read_write_lock, NULL) != 0) {
perror("Failed to initialize read-write lock");
exit(EXIT_FAILURE);
}
pthread_create(&reader_thread, NULL, thread_reader, NULL);
pthread_create(&writer_thread, NULL, thread_writer, NULL);
pthread_join(reader_thread, NULL);
pthread_join(writer_thread, NULL);
pthread_rwlock_destroy(&read_write_lock);
printf("Shared value after threads finish: %d\n", shared_value);
return 0;
}
阅读全文