Linux pthread mutex and kernel scheduler

前端 未结 2 1293
一向
一向 2021-01-20 06:22

With a friend of mine, we disagree on how synchronization is handled at userspace level (in the pthread library).

a. I think that during a pthread_mutex_lock, the th

2条回答
  •  醉酒成梦
    2021-01-20 07:08

    Some debuging with gdb for this test program:

    #include 
    #include 
    #include 
    #include 
    
    pthread_mutex_t x = PTHREAD_MUTEX_INITIALIZER;
    
    void* thr_func(void *arg)
    {
      pthread_mutex_lock(&x);
    }
    
    int main(int argc, char **argv)
    {
      pthread_t thr;
    
      pthread_mutex_lock(&x);
      pthread_create(&thr, NULL, thr_func, NULL);
      pthread_join(thr,NULL);
      return 0;
    }
    

    shows that a call to pthread_mutex_lock on a mutex results in a calling a system call futex with the op parameter set to FUTEX_WAIT (http://man7.org/linux/man-pages/man2/futex.2.html)

    And this is description of FUTEX_WAIT:

    FUTEX_WAIT

    This operation atomically verifies that the futex address uaddr still contains the value val, and sleeps awaiting FUTEX_WAKE on this futex address. If the timeout argument is non-NULL, its contents describe the maximum duration of the wait, which is infinite otherwise. The arguments uaddr2 and val3 are ignored.

    So from this description I can say that if a mutex is locked then a thread will sleep and not actively wait. And it will sleep until futex with op equal to FUTEX_WAKE is called.

提交回复
热议问题