Semaphore--synchronisation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <stdlib.h> 

char n[1024];
sem_t len;

void * read1()
{
        while(1){
                printf("Enter a string");
                scanf("%s",n);
                sem_post(&len);
        }
}

void * write1()
{
        while(1){ sleep(5);
                sem_wait(&len);
                printf("The string entered is :");
                printf("==== %s\n",n);
        }

}

int main()
{
        int status;
        pthread_t tr, tw;

        pthread_create(&tr,NULL,read1,NULL);
        pthread_create(&tw,NULL,write1,NULL);

        pthread_join(tr,NULL);
        pthread_join(tw,NULL);
        return 0;
}


I found this program in a forum and here thread1 may read one more string and thread2 displays the last read string(because of delay due tosleep(5) in write1() operation).So,serial read and write is not achieved and we can expect the same even if we dont add sem_wait(&len); sem_post(&len); in this program.Then what kind of synchronisation is achieved in this program by this semaphore addition?

what kind of synchronisation is achieved in this program by this semaphore addition?

I think you're missing the point.

The program runs in an infinite loop:
read1() reads a string into global buffer.
write1() waits for the string to be entered and prints it when it's available.

The semaphore is used to implement that syncronisation.

Did you run the program?
Topic archived. No new replies allowed.