Here is my program of Pthread Synchronization without using Mutex
#include < pthread.h>
#include < stdlib.h>
#include < unistd.h>
int mx=0;
void *thread_function1(void *arg) {
int i;
for ( i=0; i<10; i++) {
while(mx==2);
mx=1;
printf("Thread says hi-%d!\n",i);
mx=2;
}
pthread_exit(0);
}
void *thread_function2(void *arg) {
int i;
for ( i=0; i<10; i++) {
while(mx==1);
mx=2;
printf("Thread says hello-%d!\n",i);
mx=1;
}
pthread_exit(0);
}
int main() {
pthread_t mythread1, mythread2;
pthread_attr_t my_attr;
char *str;
if(pthread_create( &mythread1, NULL, thread_function1, NULL) ) {
printf("error creating thread1.");
abort();
}
if(pthread_create( &mythread2, NULL, thread_function2, NULL) ) {
printf("error creating thread2.");
abort();
}
mx=1;
if ( pthread_join (mythread1, NULL) ) {
perror("error joining thread.");
abort();
}
if ( pthread_join (mythread2, NULL) ) {
perror("error joining thread.");
abort();
}
printf("Pthread Joing Success\n");
exit(0);
}
The main disadvantage of this code, is polling, the while() statement in the 2 threads. When you use Mutex/semaphore, this polling which consume CPU time, can be avoided. I don't know the implementation of Pthread Mutex. But we can try to analyze through time command in the next session.
Next Meet Pannalam....
No comments:
Post a Comment