Quantcast
Channel: The Old New Thing
Viewing all articles
Browse latest Browse all 24428

re: This code would be a lot faster if it weren't for the synchronization

$
0
0

@Gabe:  you are completely wrong.  Consider one thread reading a value from storage, incrementing it, and writing it back, while another thread reads the same value, increments it, and writes it back.  On a single-processor system.  Disabling all interrupts is not always possible or desirable; should interrupts from the keyboard, or I/O completion, or timer expirations, be halted while a thread is running?  What about runaway threads?

Thread A can be interrupted by timer expirations after its read but before its write.  In the meantime, while Thread A is suspended, Thread B can read the (old) value (that has not been incremented by Thread A), increment it, and write it back.  Then Thread A is dispatched again, when it writes its incremented value back from its own copy.  

Thread B's increment has been LOST; its incremented value was overwritten by Thread A.

You need to realize that single-processor systems have multiple things going on at once, and you shouldn't (or can't) disable all interrupts in user code.  Critical sections are designed to prevent this.  Threads A and B *each* need to obtain a lock of some kind before reading the value, and release that lock AFTER each has written the value back.


Viewing all articles
Browse latest Browse all 24428

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>