Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Monitor (synchronization)
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
====Incorrect without synchronization==== A naive approach is to design the code with '''busy-waiting''' and no synchronization, making the code subject to race conditions: <syntaxhighlight lang="cpp"> global RingBuffer queue; // A thread-unsafe ring-buffer of tasks. // Method representing each producer thread's behavior: public method producer() { while (true) { task myTask = ...; // Producer makes some new task to be added. while (queue.isFull()) {} // Busy-wait until the queue is non-full. queue.enqueue(myTask); // Add the task to the queue. } } // Method representing each consumer thread's behavior: public method consumer() { while (true) { while (queue.isEmpty()) {} // Busy-wait until the queue is non-empty. myTask = queue.dequeue(); // Take a task off of the queue. doStuff(myTask); // Go off and do something with the task. } } </syntaxhighlight> This code has a serious problem in that accesses to the queue can be interrupted and interleaved with other threads' accesses to the queue. The ''queue.enqueue'' and ''queue.dequeue'' methods likely have instructions to update the queue's member variables such as its size, beginning and ending positions, assignment and allocation of queue elements, etc. In addition, the ''queue.isEmpty()'' and ''queue.isFull()'' methods read this shared state as well. If producer/consumer threads are allowed to be interleaved during the calls to enqueue/dequeue, then inconsistent state of the queue can be exposed leading to race conditions. In addition, if one consumer makes the queue empty in-between another consumer's exiting the busy-wait and calling "dequeue", then the second consumer will attempt to dequeue from an empty queue leading to an error. Likewise, if a producer makes the queue full in-between another producer's exiting the busy-wait and calling "enqueue", then the second producer will attempt to add to a full queue leading to an error.
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)