c - Functions sem_post, sem_wait and sleep
问题描述
I'm trying to solve the following exercise:
Machine A produces an item every 2 seconds. The AA machine assembles a product from 2 items that machine A had produced.
An AA machine can assemble a product every second, but it needs 2 items per product, so AA is waiting for 2 items from Machine A.
Each machine works in an endless loop, but the factory closes after 20 seconds and does not wait for the machines to finish working.
Write a program that allows the factory and the machines in it, organized work according to the requirements of the factory.
I have the following output, and my code needs to output the same.
I write this:
#include <pthread.h>
#include <stdio.h>
#include <string.h>
#include <semaphore.h>
sem_t sem1;
void* Machine_A() {
while(1) {
printf("Produced A\n");
sleep(2);
sem_post(&sem1);
}
}
void* Machine_AA() {
while(1) {
sem_wait(&sem1);
sem_wait(&sem1);
printf("Collected AA\n");
sleep(1);
}
}
int main() {
pthread_t threadA, threadAA;
sem_init(&sem1, 0, 0);
pthread_create(&threadA, NULL, Machine_A, NULL);
pthread_create(&threadAA, NULL, Machine_AA, NULL );
sleep(20);
return 0;
}
and I get this output:
I don't understand why machine A prints 3 times at first time and after that it works well.
If I change the code of machine A:
void* Machine_A() {
while(1) {
printf("Produced A\n");
sem_post(&sem1);
sleep(2);
}
}
I get the right output.
I don't understand why it prints Produced A
3 times.
Every time sem_wait
blocks until it becomes possible to perform the decrement.
Thanks!!
解决方案
推荐阅读
- ajax - 事件门票插件生成的 WordPress admin-ajax.php 400 错误...数据库相关?
- oracle - 有什么办法可以防止表更新?
- html - 浏览器无法将 xsl 文件识别为 xsl
- reactjs - 如何在 React-JSS 中使用“@global”
- sql - Snowflake SQL - 为 EoM 日期创建临时日期表
- javascript - 无法单击带有 HtmlUnit 的 RadioButton
- javascript - AMP 中是否有 popState 来支持浏览器历史堆栈?
- javascript - 如果 Input 元素没有值,如何禁用 LinkButton?
- android - 如何在 Android 应用中部署自定义图像处理算法?
- c# - C#GetDeclaredProperty Set Value 错误,方法 SetValue 没有重载有一个参数