在这种情况下futex如何工作? [英] How futex works in this case?

查看:102
本文介绍了在这种情况下futex如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个futex的示例代码。但我无法理解代码流....



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;

       /*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





这个代码实际上是如何表现的?



thread_f函数的触发器是什么?



等待&唤醒在这里工作??



How does actually this code is behaving??

what is the trigger for thread_f functions??

How does wait & wake working here??

推荐答案

参见 http ://unixhelp.ed.ac.uk/CGI/man-cgi?futex [ ^ ]。


这篇关于在这种情况下futex如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆