Kotlin linkedlist3/31/2023 This is why the final value is not what we expect. This problem can occur in similar other ways, for example, a thread gets past the second level, but before storing it, other threads increment and save the sharedCounter value, and when the first thread jumps in for its third step, it saves an older version of the sharedCounter. Save the temp variable to sharedCounter.īut what if one thread gets the current value, and since we are in a multi-threaded world, another thread jumps in, and tries to get the current value? Both of them will get the same value! So each of them increment that value by 1, and store the same value. Store it in a temp variable, and increment the temp variable by 1,. In the code above, In order to increment the sharedCounter, each thread is trying to do following to internally increment the sharedCounter value: What happens in this scenario is, when one person is inside the room, other people can also open the door, come in and use the room. This room has a door that when the room is occupied, is closed. In the example above, we are launching 1000 coroutines (If you don’t know what they are, just think about them as light-weight threads) on 4 threads, and each of them, increment the global value sharedCounter 1000 times, so the final value of the sharedCounter should be 1000000, but it hardly ever is, unless you get very lucky.īefore we technically explain what is happening here, Imagine there’s one thinking room (the counter) and many people (threads) want to use it but only one person is allowed at a time. Thread-unsafe code which leads to incorrect result
0 Comments
Leave a Reply.AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |