Scenario B – race condition happening

Thread A reads the value (1), posts it to the API, increments it to 2, but before it can save it back, the scheduler decides to pause thread A in favor of Thread B.

Thread B reads the value (still 1!), posts it to the API, increments it to 2, and saves it back. The scheduler then switches over to Thread A again. Thread A resumes its stream of work by simply saving the value it was holding after incrementing, which is 2.

After this scenario, even though the operation has happened twice as in Scenario A, the value saved is 2, and the API has been called twice with 1.

In a real-life situation, with multiple threads and real code performing several operations, the overall behavior of the program explodes into a myriad of possibilities. We'll see an example of this later on, and we'll fix it using locks.

The main problem with race conditions is that they make our code non-deterministic, which is bad. There are areas in computer science where non-determinism is used to achieve things, and that's fine, but in general you want to be able to predict how your code will behave, and race conditions make it impossible to do so.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.36.231