sem_wait使用示例
时间: 2023-09-16 08:14:05 浏览: 204
`sem_wait`是一个用于等待信号量的函数,其原型如下:
```
int sem_wait(sem_t *sem);
```
其中,`sem`是一个指向信号量的指针。如果信号量当前的值大于0,则将其减1并立即返回;否则,当前线程将阻塞,直到信号量的值变为大于0。
下面是一个简单的示例,演示了如何使用`sem_wait`函数等待信号量:
```c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#define MAX_THREADS 5
sem_t sem;
int counter = 0;
void *thread_func(void *arg) {
int id = *(int *)arg;
printf("Thread %d waiting for semaphore...\n", id);
sem_wait(&sem);
printf("Thread %d acquired semaphore!\n", id);
for (int i = 0; i < 10; i++) {
printf("Thread %d: counter = %d\n", id, ++counter);
sleep(1);
}
sem_post(&sem);
printf("Thread %d released semaphore!\n", id);
pthread_exit(NULL);
}
int main() {
pthread_t threads[MAX_THREADS];
sem_init(&sem, 0, 1); // 初始化信号量
int ids[MAX_THREADS];
for (int i = 0; i < MAX_THREADS; i++) {
ids[i] = i;
pthread_create(&threads[i], NULL, thread_func, &ids[i]);
}
for (int i = 0; i < MAX_THREADS; i++) {
pthread_join(threads[i], NULL);
}
sem_destroy(&sem); // 销毁信号量
return 0;
}
```
在这个示例中,我们创建了5个线程,并且将它们的ID传递给`thread_func`函数。在`thread_func`函数中,每个线程首先等待信号量,然后执行一些操作,最后释放信号量。注意到每个线程在执行操作时都会修改`counter`变量,而信号量保证了不会有两个线程同时修改`counter`变量,因此`counter`的最终值应该是50。
输出结果应该如下:
```
Thread 0 waiting for semaphore...
Thread 0 acquired semaphore!
Thread 1 waiting for semaphore...
Thread 2 waiting for semaphore...
Thread 3 waiting for semaphore...
Thread 4 waiting for semaphore...
Thread 0: counter = 1
Thread 0: counter = 2
Thread 0: counter = 3
Thread 0: counter = 4
Thread 0: counter = 5
Thread 0: counter = 6
Thread 0: counter = 7
Thread 0: counter = 8
Thread 0: counter = 9
Thread 0: counter = 10
Thread 0 released semaphore!
Thread 1 acquired semaphore!
Thread 1: counter = 11
Thread 1: counter = 12
Thread 1: counter = 13
Thread 1: counter = 14
Thread 1: counter = 15
Thread 1: counter = 16
Thread 1: counter = 17
Thread 1: counter = 18
Thread 1: counter = 19
Thread 1: counter = 20
Thread 1 released semaphore!
Thread 2 acquired semaphore!
Thread 2: counter = 21
Thread 2: counter = 22
Thread 2: counter = 23
Thread 2: counter = 24
Thread 2: counter = 25
Thread 2: counter = 26
Thread 2: counter = 27
Thread 2: counter = 28
Thread 2: counter = 29
Thread 2: counter = 30
Thread 2 released semaphore!
Thread 3 acquired semaphore!
Thread 3: counter = 31
Thread 3: counter = 32
Thread 3: counter = 33
Thread 3: counter = 34
Thread 3: counter = 35
Thread 3: counter = 36
Thread 3: counter = 37
Thread 3: counter = 38
Thread 3: counter = 39
Thread 3: counter = 40
Thread 3 released semaphore!
Thread 4 acquired semaphore!
Thread 4: counter = 41
Thread 4: counter = 42
Thread 4: counter = 43
Thread 4: counter = 44
Thread 4: counter = 45
Thread 4: counter = 46
Thread 4: counter = 47
Thread 4: counter = 48
Thread 4: counter = 49
Thread 4: counter = 50
Thread 4 released semaphore!
```
阅读全文