0

try this code block in one thread

int a = 0;

a = 1; //the thread is running on cpu A

a?   //the thread is switched and running on cpu B

so a can be 0 ?

1
  • Is a shared? How is it updated and by what threads? Without proper notation this is highly bad question Commented Aug 26, 2020 at 11:17

1 Answer 1

0

No, a must be 1 because there is a happens-before relationship between the assignment a = 1 and the value of a being read later by the same thread.

If x and y are actions of the same thread and x comes before y in program order, then hb(x, y).

Sign up to request clarification or add additional context in comments.

8 Comments

When a context switch happens, either the value of a is written back to heap, or its value is stored in the process control block. See also stackoverflow.com/questions/30774550/…
so the system needs to track all the variables that the thread modified?
if there are two thread switched, they both write 'a' back to heap? it seems the happens-before does not work
Yes but typically it doesn't track individual variables because a variable is a programmer concept. Instead the memory management unit tracks cache lines. On the other hand, the variable may be stored in a register, and not be present on the heap at all.
In your code, a is a local variable. That means each thread has a copy of its own of a.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.