#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
// 定义信号量
sem_t semaphore;
// 共享资源
int sharedResource = 0;
// P操作
void P(sem_t *sem) {
sem_wait(sem);
}
// V操作
void V(sem_t *sem) {
sem_post(sem);
}
// 线程1函数
void* thread1(void* arg) {
for (int i = 0; i < 5; i++) {
P(&semaphore);
sharedResource++;
printf("Thread 1: sharedResource = %d\n", sharedResource);
V(&semaphore);
}
return NULL;
}
// 线程2函数
void* thread2(void* arg) {
for (int i = 0; i < 5; i++) {
P(&semaphore);
sharedResource--;
printf("Thread 2: sharedResource = %d\n", sharedResource);
V(&semaphore);
}
return NULL;
}
int main() {
// 初始化信号量为1
sem_init(&semaphore, 0, 1);
pthread_t tid1, tid2;
// 创建线程1
if (pthread_create(&tid1, NULL, thread1, NULL) != 0) {
printf("\n ERROR creating thread1");
return 1;
}
// 创建线程2
if (pthread_create(&tid2, NULL, thread2, NULL) != 0) {
printf("\n ERROR creating thread2");
return 1;
}
// 等待线程1结束
if (pthread_join(tid1, NULL) != 0) {
printf("\n ERROR joining thread");
return 2;
}
// 等待线程2结束
if (pthread_join(tid2, NULL) != 0) {
printf("\n ERROR joining thread");
return 2;
}
// 销毁信号量
sem_destroy(&semaphore);
return 0;
}
代码各部分作用解释:
- 信号量定义和共享资源:
sem_t semaphore;
定义一个信号量变量。
int sharedResource = 0;
定义一个共享资源,初始值为0。
- P操作:
void P(sem_t *sem) { sem_wait(sem); }
实现P操作,sem_wait
函数会将信号量的值减1,如果信号量的值为0,则线程会阻塞,直到信号量的值大于0。
- V操作:
void V(sem_t *sem) { sem_post(sem); }
实现V操作,sem_post
函数会将信号量的值加1,唤醒可能被阻塞的线程。
- 线程函数:
thread1
和thread2
函数分别对共享资源进行加1和减1操作。在操作前调用P操作获取信号量,操作后调用V操作释放信号量,以此控制对共享资源的访问。
- 主函数:
sem_init(&semaphore, 0, 1);
初始化信号量,值为1,表示共享资源初始可用。
pthread_create
创建两个线程。
pthread_join
等待两个线程执行完毕。
sem_destroy(&semaphore);
销毁信号量,释放资源。