Reputation: 3331
The following code shows a producer-consumer example: Once a product is produced, the consumer will get this product.
But I'm surprised that the consumer will sill get a product when there is no product.
#include <stdlib.h>
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <semaphore.h>
#define NUM 5
int queue[NUM];
int i;
sem_t *blank_number, *product_number;
void *producer(void *arg) {
int p = 0;
while (1) {
sem_wait(blank_number);
queue[p] = rand() % 1000 + 1;
printf("Produce queue[%d]:%d\n", p, queue[p]);
i = sem_post(product_number);
//printf("i_p=%d\n", i);
p = (p+1)%NUM;
sleep(rand()%5);
}
}
void *consumer(void *arg) {
int c = 0;
while (1) {
sem_wait(product_number);
printf("Consume queue[%d]:%d\n", c, queue[c]);
queue[c] = 0;
i = sem_post(blank_number);
//printf("i_c=%d\n", i);
c = (c+1)%NUM;
sleep(rand()%5);
}
}
int main(int argc, char *argv[]) {
pthread_t pid, cid;
//set blank_number to NUM
blank_number = sem_open("blank_number", O_CREAT, S_IRWXU, NUM);
if(blank_number == SEM_FAILED){
perror("open blank_number");
return 1;
}
//set product_number to 0
product_number = sem_open("product_number", O_CREAT, S_IRWXU, 0);
if(product_number == SEM_FAILED){
perror("open product_number");
return 1;
}
pthread_create(&pid, NULL, producer, NULL);
pthread_create(&cid, NULL, consumer, NULL);
pthread_join(pid, NULL);
pthread_join(cid, NULL);
sem_close(blank_number);
sem_close(product_number);
return 0;
}
In my test result, there is only one product: 808, but the consumer gets two products: 808 and 0;
$ sudo ./a.out
Produce queue[0]:808
Consume queue[0]:808
Consume queue[1]:0
Is there any wrong in my code?
Upvotes: 0
Views: 3240
Reputation: 36391
Your problem is that you never deleted your semaphores. So when you open them you recover some old/bad state. Try to open with O_EXCL
you will be able to observe the problem.
Write a simple command to delete them with sem_unlink()
or initialize them before using them with semctl
.
You also need to set the appropriate values in sem_open
not 022...
Alos note that POSIX named semaphores should have a name starting with /
.
Change the beginning of your main to :
sem_unlink("blank_number");
sem_unlink("product_number");
//set blank_number to 1
blank_number = sem_open("blank_number", O_CREAT|O_EXCL, S_IRWXU, 1);
if(blank_number == SEM_FAILED){
perror("open blank_number");
return 1;
}
//set product_number to 0
product_number = sem_open("product_number", O_CREAT|O_EXCL, S_IRWXU, 0);
if(product_number == SEM_FAILED){
perror("open product_number");
return 1;
}
Upvotes: 2
Reputation: 3496
Maybe try to use sem_init
with an unnamed semaphore instead of sem_open
:
sem_t semaphore;
int ret = sem_init(&semaphore, 0, 0);
Upvotes: -1