I have a sample code of futex. But i couldnt understand the code flow....
#include <stdio.h>
#include <pthread.h>
#include
#include <syscall.h>
#include <unistd.h>
#define NUM 50
int futex_addr;
int futex_wait(void* addr, int val1){
return syscall(SYS_futex,&futex_addr,val1, NULL, NULL, 0);
}
int futex_wake(void* addr, int n){
return syscall(SYS_futex, addr, FUTEX_WAKE, n, NULL, NULL, 0);
}
void* thread_f(void* par){
int id = (int) par;
futex_addr = 0;
futex_wait(&futex_addr,0);
printf("Thread %d starting to work!\n",id);
return NULL;
}
int main(){
pthread_t threads[NUM];
int i;
for (i=0;i<num;i++){>
pthread_create(&threads[i],NULL,thread_f,(void *)i);
}
printf("Everyone wait...\n");
sleep(1);
printf("Now go!\n");
futex_wake(&futex_addr,50);
sleep(1);
printf("Main is quitting...\n");
return 0;
}
the output comes like this :
Everyone wait...<br />
Now go!<br />
Thread 0 starting to work!<br />
Thread 1 starting to work!<br />
Thread 2 starting to work!<br />
Thread 3 starting to work!<br />
Thread 4 starting to work!<br />
Thread 5 starting to work!<br />
Thread 6 starting to work!<br />
Thread 7 starting to work<br />
Thread 8 starting to work!<br />
Thread 9 starting to work!<br />
.<br />
.<br />
Main is quitting
How does actually this code is behaving??
what is the trigger for thread_f functions??
How does wait & wake working here??