/MY PROGRAM ARE COMPILED IN FEDORA15 ..WITH 4.6 gcc compiler...../
/*A semaphore is used to synchronise the threads*/
2 //In this function semaphore may be acquired by any of thread at any time...so no sy nchronisation will be maintains in executing the threads ...
3 //so global data may be changed by any of thread at any instant of time
4 //suppose there r four fun open..read ..write..close..close may be executed 1st befo re read
5 //if i applied semaphore before pthread_create...work of pthread_create is only to c reate a thread ..not to wait finishing of function started when this thread created. .so in mid of execution of that func..it will release the semaphore & give it to ano ther pthread_create
6 //when main ends ....every thread will be finished..
7 //but benefit of semaphore will be seen when i will use it globaly..means for more t han one process....it will sychronise threads b/w two distinct process...
8 //suppose i have open write read close function in two applications & both applicati ons will execute at same time as foreground process as used & b/w files...then it wi ll do write of 1st app ...then write of another app..
9 //i want 1st open write read & close occur in 1st app...then open write read & close in another app...so could be synchronised by using global semaphore of threads
10 #include<stdio.h>
12 #include<stdlib.h>
13 #include<string.h>
14 #include<pthread.h>
15 #include<semaphore.h>
16 void* thread_fun1(void*);
17 void* thread_fun2(void*);
18 void* thread_fun3(void*);
19 void* thread_fun4(void*);
20 char buff[24],set[20];//used two global variables...shared by all threads
21 sem_t mutex;//variable of semaphore is declared
22 int main()
23 {
24 int lv;
25 void* retval;
26 char *message="THIS IS LINUX";
27 pthread_t tid1,tid2,tid3,tid4;
28 if(!sem_init(&mutex,0,1))//semid will in mutex..2nd arg is value of pshared. ...i.e.if pshared=0 means this semaphore may be used local to this process ...if ps hared=1...means this same semaphore may be used extern to this process
127 printf("set*****************=%s\n",buff);//again prints changed data if threads r in synchronised way otherwise...not any continuty will be maintained ..one time co pied data into buff may be printed in both of other threads...
128 printf("...whose priority is %d\n",g);
129 //pthread_exit("MAC");
130 if(!sem_post(&mutex))
131 printf("sem release in thread4 succesfully\n");