Let me make sure I understand C pthread mutex -


I have a global variable flag , a function it () , And a function that () . Now, main () , this () and that () are all opportunities where they need to read and / or write the flag. Is . To use a mute x properly I'll need it:

  1. Announce a pthread_mutex_t and start it.
  2. Create threads for (this) and that () and pthread_join () because it's me To wait for the main to finish on and before exiting it () .
  3. Anywhere in the code, it should be main () , it () , or that () , where < Code> flag reading or writing, call pthread_mutex_lock () then [read / write] flag then call pthread_mutex_unlock () < / Code>

    Is that correct?

    I do not plan on doing this if I want to see flag in an infinite loop in :

      while (flag! = Value) continues;   

    Where do you lock () and unlock () mutex and other threads with the flag Code> main () running continuously on it?

    1 - 2 - 3 - correct.

    Now, if you write that loop, <3p>

    • As a result of 3, the main thread will catch the lock, and other threads will not be able to get the lock, so In fact, you have created an infinite loop.
    • If you do not lock, this will not work, it depends on CPU architecture (firstly, flag must be updateable atomically, and The other core needs to see those changes. Not all architectures are guaranteed). Even if this works, it is still a busy wait loop, and it should not be used.

      As Ben said in his comment, you want to use the condition variable for signaling (note :)

      where do you lock () Will and Unlock () Mute X

      In the form of a thumb of the rule, to reduce the dispute, keep the lock in brief. This lock can be as easy as + reading + unlock, but if the sequence of operations depends on the fact that the flag should not be changed, keep the lock as necessary as possible.

Comments

Popular posts from this blog

excel vba - How to delete Solver(SOLVER.XLAM) code -

github - Teamcity & Git - PR merge builds - anyway to get HEAD commit hash? -

ios - Replace text in UITextView run slowly -