Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have a sample code of futex. But i couldnt understand the code flow....

C++
#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;

       /*go to sleep*/
       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");
       /*wake threads*/
       futex_wake(&futex_addr,50);

       /*give the threads time to complete their tasks*/
           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??
Posted
Updated 30-Jun-14 2:10am
v2
Comments
Keith Barrow 30-Jun-14 8:11am    
Hi - I have updated your question for you with the correct code tags. It'll help you get a quicker answer in the future if you do this yourself as people won't take the time to read stuff that is hard to read.
Prashanth Cm 30-Jun-14 8:17am    
thanks keith.. can you tell me how to set these tags??

1 solution

 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900