Results 1 to 4 of 4
In Linux C Programming
I have a 'C' program of Producer-Consumer problem is solved through implementation of Semaphore.
PROGRAM::
------------------------------------------------------------------------------------------------------
#include<stdio.h>
#include<pthread.h>
#include<semaphore.h>
#include <sys/sem.h>
void cons();
void pro();
int ...
- 08-03-2009 #1Just Joined!
- Join Date
- May 2009
- Posts
- 7
Declaring a Semaphore in Linux C
In Linux C Programming
I have a 'C' program of Producer-Consumer problem is solved through implementation of Semaphore.
PROGRAM::
------------------------------------------------------------------------------------------------------
#include<stdio.h>
#include<pthread.h>
#include<semaphore.h>
#include <sys/sem.h>
void cons();
void pro();
int buffer[5], rear=-1; front=0;
int main()
{
pthread_t t1, t2;
sem_init(&s, 0, 1);
sem_init(&n, 0, 0);
sem_init(&e, 0, 5);
pthread_create(&t1, NULL, (void *) cons, NULL);
pthread_create(&t2, NULL, (void *) pro, NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
sem_destroy(&s);
sem_destroy(&n);
sem_destroy(&e);
return(0);
}
void pro()
{
while (1)
{
int x;
sem_wait(&e);
sem_wait(&s);
x=random();
rear=(rear+1)%5);
buffer[rear]=x;
printf("Number produced at %d is %d", rear, buffer[rear]);
sem_post(&s);
sem_post(&n);
sleep(2);
}
}
void cons()
{
while(1)
{
sem_wait(&n);
sem-wait(&s);
printf ("Number consumed at %d is %d", front, buffer[front]);
front=((front+1)%5);
sem_post(&s);
sem_post(&e);
sleep(5);
}
}
------------------------------------------------------------------------------------------------------
In above program:
What is &s in the initialization of the semaphore?
What is 's'?
When I run my program it gives me error similar to:
****
error
****
5b.c: In function ‘main’:
5b.c:16: error: ‘s’ undeclared (first use in this function)
5b.c:16: error: (Each undeclared identifier is reported only once
****
How can I eliminate this error? I don't know much about semaphore.
Thank you.
- 08-03-2009 #2
This is not a problem with semaphores but a more fundamental error of not declaring/defining a variable you use.
Debian GNU/Linux -- You know you want it.
- 08-03-2009 #3Just Joined!
- Join Date
- May 2009
- Posts
- 7
how to declare that variable.
can u pleaze tell me
What will be the type of that variable 's'?
Thank you.
- 08-03-2009 #4Just Joined!
- Join Date
- Jul 2009
- Posts
- 58
# man sem_init
will give you the decl and the type.


Reply With Quote