Ranter
Join devRant
Do all the things like
++ or -- rants, post your own rants, comment on others' rants and build your customized dev avatar
Sign Up
Pipeless API
From the creators of devRant, Pipeless lets you power real-time personalized recommendations and activity feeds using a simple API
Learn More
Comments
-
I don't know C sharp, but it looks like the first task runs indefinitely and you never even get to the rest of it. Am I wrong?
-
Undefined behavior.
As soon as a task finishes incrementing the variable, it releases the lock, so the second task can take it, but sometimes the second task can't manage to take it, and the lock is re-acquired by the first task.
Pretty random. I guess based on OS behavior and thread prioritization. -
@Mitiko locks a lock :)
A lock can be any object. A thread can lock that object so that any other thread that wants to lock it, is forced to wait for it to unlock.
This way you avoid 2 threads accessing and modifying the same stuff at the same time. You can lock a DB connection for example, an open file, a queue, list, or any other shared resource. or if you can't identify that resource, lock a random object shared among threads.
Lock is a code block, like so:
lock(someStuff) {
... code here...
} // unlocks here
Related Rants
What happens and why
undefined
csharp
thread lock
race conditions
undefined behavior