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 ?
CodePudding user response:
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).
CodePudding user response:
Variables with automatic storage - such as the parameter x
- are distinct each time their scope is entered - in this case each time the function is called.
This is true when the function calls are from different threads, but also when the function is re-entered from the same thread which can occur in presence of recursion, or asynchronous signals.
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?
This isn't possible, because each x
is a distinct object.
when and how is memory separate in c multithreading?
The entire memory space is shared across all threads.
But whether a variable names the same object is a different matter. Automatic variables are distinct each time their scope is entered as I mentioned earlier. Thread local variables name a distinct object in each thread. Static variables name the same object in all threads and are very susceptible to multi-threading bugs.