As c/c++ standard said, the size of char
must be 1
. As my understanding, that means CPU guarantees that any read or write on a char
must be done in one instruction.
Let's say we have many threads, which share a char
variable:
char target = 1;
// thread a
target = 0;
// thread b
target = 1;
// thread 1
while (target == 1) {
// do something
}
// thread 2
while (target == 1) {
// do something
}
In a word, there are two kinds of threads: some of them are to set target
into 0
or 1
, and the others are to do some tasks if target == 1
. The goal is that we can control the task-threds through modifying the value of target
.
As my understanding, it doesn't seem that we need to use mutex/lock
at all. But my coding experience gave me a strong feeling that we must use mutex/lock
in this case.
I'm confused now. Should I use mutex/lock
or not in this case?
You see, I can understand why we need mutex/lock
in other cases, such as i++
. Because i++
can't be done in only one instruction. So can target = 0
be done in one instruction, right? If so, does it mean that we don't need mutex/lock
in this case?
Well, I know that we could use std::atomic
, so my question is: is it OK to not use neither mutex/lcok
nor std::atomic
.