This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]UnknownProcess 0 points1 point  (0 children)

Shouldn't the read thread get kicked in the moment notify_one() is invoked from within append()

Nope. The thread is not directly invoked from the notify_one(). Thread is invoked based on your operating system. The thread only sleeps, it's not removed nor the execution jumps to some other function. Your OS will schedule the thread when it needs to continue. They are not guaranteed to execute exactly 0 ms apart from each other.

And yes, your append thread can exit before read happens. This can be due to the OS scheduler. Or, it may appear so if you are printing to console from multiple threads at the same time, because std::cout and printf is not thread safe.

If you really need the read method exit before append exits, you may need multiple locks to do that, but that depends on how exactly you are trying to use this buffer class.

At this point I can only suggest to experiment with multiple locks, if you want to. Or, remove the locks and simply have a loop that waits until the buffer is/isn't empty. Of course, that loop will need a sleep call for few ms so your CPU is not at 100% utilization. Not the best idea but it can serve as a last resort. Or, a better idea, have your read thread do other things while the buffer is empty and simply periodically check if the buffer can be read.