Created
November 21, 2014 17:16
-
-
Save ka4tik/685e1ceccc676ca6a7aa to your computer and use it in GitHub Desktop.
pearson pthread c++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using namespace std; | |
| #include <unistd.h> /* Symbolic Constants */ | |
| #include <sys/types.h> /* Primitive System Data Types */ | |
| #include <errno.h> /* Errors */ | |
| #include <stdio.h> /* Input/Output */ | |
| #include <stdlib.h> /* General Utilities */ | |
| #include <pthread.h> /* POSIX Threads */ | |
| #include <string.h> /* String handling */ | |
| #include <iostream> | |
| int flag[2]; | |
| int turn; | |
| #define randomdelay usleep(rand()%20) | |
| void *peterson(void * ptr) | |
| { | |
| int *temp = (int *) ptr; | |
| int i = *temp; | |
| cout << "Process " << i << "created" << endl; | |
| int j = 1-i; | |
| while(1) | |
| { | |
| // Non-critical section | |
| // We do not really care what happens here. But we care that it may take different times. Hence, will invoke a random number generator for doing wait | |
| randomdelay; | |
| flag[i] = 1; | |
| // There is a possibility that the thread may get swapped out here. So, add a random delay | |
| randomdelay; | |
| turn = j; | |
| randomdelay; | |
| while(flag[j]==1 && turn==j); | |
| // Entering CS | |
| cout << "Entering CS process " << i << endl; | |
| sleep(10); | |
| cout << "Exiting CS process " << i << endl; | |
| } | |
| } | |
| int main() | |
| { | |
| flag[0] = 0; | |
| flag[1] = 0; | |
| turn = 0; // Not needed since turn is never used without being set first | |
| pthread_t thread1, thread2; /* thread variables */ | |
| int p0 = 0; | |
| int p1 = 1; | |
| pthread_create(&thread1, NULL, peterson, (void *) &p0); | |
| pthread_create(&thread2, NULL, peterson, (void *) &p1); | |
| pthread_join(thread1, NULL); | |
| pthread_join(thread2, NULL); | |
| /* exit */ | |
| exit(0); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment