user3238098
user3238098

Reputation:

C Semaphore understanding

Let me explain better , i now that variable *contador needs semaphores ...

This exercise asked us to put semaphores so this two program works and *contador doesn't get over 200...

while ((*contador)==MAX); was made by the University Teacher in one exam ,and is what i am trying to understand.

1. //program people enter
2. #define MAX 200 
3. int main(int argc, char* argv[]) { 
4. int *contador; 
5. 
6. int fd=shm_open("/contador",O_RDWR|O_CREAT,S_IRUSR|S_IWUSR); 
7. 
8. int ret=ftruncate(fd,sizeof(int)); 
9. 
10. contador=mmap(0,sizeof(int),PROT_READ|PROT_WRITE,MAP_SHARED,fd,0); 
11. 
12. while ((*contador)==MAX); 
13   sem_wait();
14. (*contador)++; 
15   sem_post();
16. } 




1. //program people get out
2. int main(int argc, char* argv[]) { 
3. int *contador; 
4. 
5. int fd=shm_open("/contador",O_RDWR|O_CREAT,S_IRUSR|S_IWUSR); 
6. 
7. int ret=ftruncate(fd,sizeof(int)); 
8. 
9. contador=mmap(0,sizeof(int),PROT_READ|PROT_WRITE,MAP_SHARED,fd,0); 
10. sem_wait();
11. (*contador)--; 
12  sem_post();
13. } 

Upvotes: 2

Views: 134

Answers (1)

zmo
zmo

Reputation: 24802

well, as your code is written, while ((*contador)==MAX); should block infinitely… until the value of *contador gets equal to MAX.

Upvotes: 1

Related Questions