0

I have a code which puts threads to sleep using futex_wait syscall. how can i put a process to sleep using futex_wait syscall?

I understand this program, it creates the thread and put them on sleep and then calls the futex_Wake syscall to wake the thread and futex_wake should return the number of threads it has woken up

Sample Code:

#include <stdio.h>
#include <pthread.h>
#include <linux/futex.h>
#include <syscall.h>
#include <unistd.h>

#define NUM 2

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){
    int msecs = 0;
    int waked = 0;
    while(1){
        sleep(1);
        msecs++;
        waked = syscall(SYS_futex, addr, FUTEX_WAKE, n, NULL, NULL, 0);
        if (waked == n)
            break;
        if (msecs > 100){
            printf("Wake timedout\n");
            return 0;
        }
    }
    return waked;
}

void* thread_f(void* par) {
        int id = (int) par;

    /*go to sleep*/
    futex_addr = 0;
    int ret = futex_wait(&futex_addr,0);
    printf("Futex_wait_returned %d\n", ret);

    // 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*/
    int ret = futex_wake(&futex_addr, NUM);
    printf("No of futex_wake processes are %d\n", ret);

    /*give the threads time to complete their tasks*/
    sleep(1);

    printf("Main is quitting...\n");
        return 0;
}

I am quite new to it, so i want to understand what changes should i make to put a process to sleep using futex

anjali rai
  • 185
  • 1
  • 1
  • 14
  • I am not convinced that you can do that in a guaranteed manner, even with constraints on the design/implementation of the process threads. – Martin James Feb 22 '21 at 09:38
  • In futex_wait02, they are able to put a sleep using futex_wait for pid https://github.com/linux-test-project/ltp/blob/master/testcases/kernel/syscalls/futex/futex_wait02.c – anjali rai Feb 22 '21 at 10:04

0 Answers0