Is it safe to read an integer variable that's being concurrently modified without locking?

前端 未结 12 1367
青春惊慌失措
青春惊慌失措 2020-12-02 09:03

Suppose that I have an integer variable in a class, and this variable may be concurrently modified by other threads. Writes are protected by a mutex. Do I need to protect re

12条回答
  •  不知归路
    2020-12-02 09:21

    Both reading / writing to variables with concurrency must be protected by a critical section (not mutex). Unless you want to waste your whole day debugging.

    Critical sections are platform-specific, I believe. On Win32, critical section is very efficient: when no interlocking occur, entering critical section is almost free and does not affect overall performance. When interlocking occur, it is still more efficient, than mutex, because it implements a series of checks before suspending the thread.

提交回复
热议问题