In multithreading (with std::thread for example), the process memory is shared between threads. However, does this extend to a function being called with two different arguments?
A silly example:
int add_two_in_ridiculous_fashion(int x) {
x++;
std::this_thread::sleep(1s);
x++;
return x;
}
While the thread is sleeping, another thread rolls in and replaces x with a different value, and the two threads return the latter's value + 1 and + 2 respectively. Is this possible?
If yes, is there a lock-free approach of preventing this in C++?
PMF :
No, this is not going to cause any problems. Each thread gets its own stack, and local variables and arguments (the x in your case) are on the stack and therefore separate for each thread. Member variables of a class or global variables are shared across different threads (for the same object instance).",
2021-11-11T18:09:34