#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#define ARRAY_SIZE 5
int sharedArray[ARRAY_SIZE];
pthread_mutex_t mutex;
void* writeThread(void* arg) {
for (int i = 0; i < ARRAY_SIZE; i++) {
pthread_mutex_lock(&mutex);
sharedArray[i] = i;
printf("Write thread: Wrote %d to sharedArray[%d]\n", i, i);
pthread_mutex_unlock(&mutex);
sleep(1);
}
return NULL;
}
void* readThread(void* arg) {
for (int i = 0; i < ARRAY_SIZE; i++) {
pthread_mutex_lock(&mutex);
printf("Read thread: Read %d from sharedArray[%d]\n", sharedArray[i], i);
pthread_mutex_unlock(&mutex);
sleep(1);
}
return NULL;
}
int main() {
pthread_t writeTid, readTid;
// 初始化互斥锁
pthread_mutex_init(&mutex, NULL);
// 创建写线程
if (pthread_create(&writeTid, NULL, writeThread, NULL) != 0) {
printf("\n ERROR creating thread");
return 1;
}
// 创建读线程
if (pthread_create(&readTid, NULL, readThread, NULL) != 0) {
printf("\n ERROR creating thread");
return 1;
}
// 等待写线程结束
if (pthread_join(writeTid, NULL) != 0) {
printf("\n ERROR joining thread");
return 2;
}
// 等待读线程结束
if (pthread_join(readTid, NULL) != 0) {
printf("\n ERROR joining thread");
return 2;
}
// 销毁互斥锁
pthread_mutex_destroy(&mutex);
return 0;
}
- 互斥锁初始化:
- 在
main
函数中,使用pthread_mutex_init(&mutex, NULL);
来初始化互斥锁mutex
。NULL
表示使用默认的互斥锁属性。
- 加锁:
- 在写线程
writeThread
和读线程readThread
中,在访问共享数组sharedArray
之前,使用pthread_mutex_lock(&mutex);
来加锁,以防止其他线程同时访问共享数组,保证数据访问的一致性。
- 解锁:
- 在写线程和读线程访问完共享数组之后,使用
pthread_mutex_unlock(&mutex);
来解锁,允许其他线程获取锁并访问共享数组。
- 线程创建与等待:
- 使用
pthread_create
函数分别创建写线程和读线程。
- 使用
pthread_join
函数等待两个线程执行完毕。
- 互斥锁销毁:
- 在程序结束前,使用
pthread_mutex_destroy(&mutex);
来销毁互斥锁,释放相关资源。