Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CRITICAL_SECTION for set and get single bool value

now writing complicated class and felt that I use to much CRITICAL_SECTION.

As far as I know there are atomic operations for some types, that are always executed without any hardware or software interrupt.

I want to check if I understand everything correctly.

  • To set or get atomic value we don't need CRITICAL_SECTION because doing that there won't be interrupts.
  • bool is atomic.

So there are my statements, want to ask, if they are correct, also if they are correct, what types variables may be also set or get without CRITICAL_SECTION?

P. S. I'm talking about getting or setting one single value per method, not two, not five, but one.

like image 201
ST3 Avatar asked Dec 16 '22 07:12

ST3


2 Answers

  1. You don't need locks round atomic data, but internally they might lock. Note for example, C++11's std::atomic has a is_lock_free function.
  2. bool may not be atomic. See here and here
like image 134
doctorlove Avatar answered Dec 23 '22 10:12

doctorlove


Note: This answer applies to Windows and says nothing of other platforms.

There are no InterlockedRead or InterlockedWrite functions; simple reads and writes with the correct integer size (and alignment) are atomic on Windows ("Simple reads and writes to properly-aligned 32-bit variables are atomic operations.").

(and there are no cache problems since a properly-aligned variable is always on a single cache line).

However, reading and modifying such variables (or any other variable) are not atomic:

  • Read a bool? Fine. Test-And-Set a bool? Better use InterlockedCompareExchange.
  • Overwrite an integer? great! Add to it? Critical section.
like image 24
Medinoc Avatar answered Dec 23 '22 10:12

Medinoc