Reputation: 1461
I had this as an interview question a while back, but I wasn't sure of the answer.
If you calculate c = c+1 with 100 threads, do you need a lock?
Upvotes: 1
Views: 178
Reputation: 30285
Yes. The reason is that the statement c = c + 1
is actually (about) three low level statements:
1. read c from the memory
2. increment c by one
3. store c back to the memory
If two threads execute (1)
, they will both increment c
to the same value and store it. So instead of being incremented twice, c
will be incremented only once.
Upvotes: 1
Reputation: 171178
Yes, in pretty much every programming language that supports concurrency.
Upvotes: 0