Last active
September 9, 2015 07:56
-
-
Save abhinavsingh/1c8cdaf06ecaa68898cd to your computer and use it in GitHub Desktop.
What's the real order? Order in which friend threads were spawned or the ticket id that they came back with?
This file contains 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
#include <stdio.h> | |
#include <stdlib.h> | |
#include <pthread.h> | |
static int ticketid = 0; | |
pthread_mutex_t lock; | |
// buyticket function remote dial a central store to obtain ticket id | |
void * buyticket() { | |
int *id = (int *)malloc(sizeof(int)); | |
pthread_mutex_lock(&lock); | |
*id = ticketid++; | |
pthread_mutex_unlock(&lock); | |
return id; | |
} | |
void * friend(void *arg) { | |
return buyticket(); | |
} | |
int main() { | |
// N friends one by one to go buy ticket | |
int N = 10; | |
int i; | |
pthread_t friends[N]; | |
for (i=0; i<N; i++) { | |
// imagine spawn of thread as u saying to friends on Node A, B, C ... to buy a ticket in order | |
pthread_create(&friends[i], NULL, friend, NULL); | |
} | |
// wait for friends to come back | |
int *id; | |
for (i=0; i<N; i++) { | |
pthread_join(friends[i], (void **)&id); | |
printf("friend id %d, ticket id %d\n", i, *id); | |
free(id); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This code is not to say that above strategy is correct, but more to imply that how ordering of operations are simply lost as soon as you start to multi-thread the client side.