What part of memory does a mutex lock? (pthreads)

前端 未结 7 1991
独厮守ぢ
独厮守ぢ 2021-01-02 15:34

All the documentation I\'ve read on the pthreads mutex states only that a mutex prevents multiple threads from accessing shared memory, but how do you specify in the program

7条回答
  •  不知归路
    2021-01-02 16:14

    A mutex locks itself and that's all it locks. It does not lock other memory, it does not lock code. You can design your code so that something other than just the mutex is protected but that's down to how you design the code, not a feature of the mutex itself.

    You can tell it doesn't lock data memory because you can freely modify the memory when the mutex is locked by someone else just by not using the mutex:

    thread1:            thread2:
        lock mtx            set i to 4  // i is not protected here
        set i to 7
        unlock mtx
    

    To say it locks code is also not quite right since you can run all sort of different sections of code under the control of a single mutex.

    And, if someone manages to get to the code within a mutex block without first claiming the mutex, it can freely run the code even when someone else has the mutex locked:

    threadN:
        if thread_id == 2: goto skip_label1
        lock mtx
      :skip1_label1
    
        set i to 7              // not as protected as you think
    
        if thread_id == 2: goto skip_label2
        unlock mtx
      :skip1_label2
    

提交回复
热议问题