Lock free synchronization

后端 未结 3 650
盖世英雄少女心
盖世英雄少女心 2021-02-15 16:55

My question is related to multithreading lock-free synchronization. I wanted to know the following:

  1. What are general approaches to achieve this? I read somewher

3条回答
  •  广开言路
    2021-02-15 17:03

    Compare and swap is useful, but there is an even simpler (so called 'lock-free') technique that is useful in certain producer/consumer use cases that might be useful so I will mention it.

    Imagine you have a function doWork() that writes to a buffer.

    1. Thread A initializes a volatile boolean variable (flag) to false that is accessible by both Thread A and creates a volatile buffer object that doWork will output to Thread B (Global, etc).
    2. Thread A creates thread B, which calls doWork().
    3. Thread B's doWork() begins creating/writing to the buffer. When finished, it sets the boolean to true.
    4. Thread A can poll a global boolean flag that starts out false. When it turns true (non false), it can access the data in the buffer object, assured that is finished. Between polls Thread A can do other work. (So for example it polls once in an update call and does not wait for a true value). This doesn't take into account error handling, but this can also be handled within the buffer.

    This only works because A only reads and B only writes, but this use case is fairly common for 'background worker' threads. This will only sure to work on Java or C# where volatile comes with the guarantees.

提交回复
热议问题