What exactly is a critical section?

后端 未结 3 1721
伪装坚强ぢ
伪装坚强ぢ 2021-01-18 03:06

Just want a little clarity on the this. Imagine I use the windows api of EnterCriticalSection. I call all of them with EnterCriticalSection(&criticalsection);

3条回答
  •  一生所求
    2021-01-18 03:36

    See this:

    Consider a variable

    int k
    

    two threads are operating on k with this statement

    k+=100;
    

    Now assume k equals to 0. The first thread starts to read k, find k=0, then add k by 100. Then the second thread starts to read k before the 1st thread write k=100 back. Then the second thread will assume k=0 and add it by 100 and finally after two threads join k=100 not expected 200. This is the reason we set k+=100 a critical section.

提交回复
热议问题