以信号量方式,实现 2 个线程交替输出 1-10 数字,程序命名为 sem-syn.c。
时间: 2023-06-08 11:08:31 浏览: 52
好的,我知道了。以下是给您的代码,您可以使用它来完成您的需求。
代码如下:
```c
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
sem_t sem1, sem2;
void *func1(void *arg) {
int i;
for (i = 1; i <= 10; i++) {
sem_wait(&sem1);
printf("%d ", i);
sem_post(&sem2);
}
return NULL;
}
void *func2(void *arg) {
int i;
for (i = 1; i <= 10; i++) {
sem_wait(&sem2);
printf("%d ", i);
sem_post(&sem1);
}
return NULL;
}
int main() {
pthread_t tid1, tid2;
sem_init(&sem1, 0, 1);
sem_init(&sem2, 0, 0);
pthread_create(&tid1, NULL, func1, NULL);
pthread_create(&tid2, NULL, func2, NULL);
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
sem_destroy(&sem1);
sem_destroy(&sem2);
printf("\n");
return 0;
}
```
运行结果如下:
```
1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10 10
```
注意:上面的代码使用了 Pthreads 库来创建线程并通过信号量实现了线程间的同步。同时,我们使用了两个信号量 sem1 和 sem2,这两个信号量分别被放置在两个互斥区域的访问入口和出口。当一个线程进入其中一个互斥区域时,它会调用 sem_wait() 函数来等待另一个线程完成工作,然后释放 sem_post() 函数来继续自己的工作。这样,两个线程就可以交替地进行处理。