我有一个 futex 的示例代码。但我无法理解代码流......
#include <stdio.h>
#include <pthread.h>
#include <linux/futex.h>
#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;
}
输出是这样的:
Everyone wait...
Now go!
Thread 0 starting to work!
Thread 1 starting to work!
Thread 2 starting to work!
Thread 3 starting to work!
Thread 4 starting to work!
Thread 5 starting to work!
Thread 6 starting to work!
Thread 7 starting to work
Thread 8 starting to work!
Thread 9 starting to work!
.
.
Main is quitting
这段代码实际上是如何表现的?
thread_f 函数的触发器是什么?
等待和唤醒在这里如何工作?