Thanks to commenters and answer posts. I solved my problem using mutexes and condition variables. Just wanted to mention that this and similar questions are quiet common and may be searched by prompts like "Multithreaded queue", "Queue synchronization", "Thread-safe queue" and "Producer Consumer problem".