Reputation: 629
I have a very time sensitive task in my main thread. However, I would also like to simultaneously print some information about this task.
Problem: cout
takes some time to execute and therefore slows down the time sensitive task in the main thread.
Idea: I thought about creating an extra thread which handles the output. To communicate between the main thread and the newly created thread, I thought about a vector which includes the strings that should be printed. In the newly created thread an infinite while loop would print these strings one after another.
Problem with the idea: Vectors are not thread safe. Therefore, I'm worried that locking and unlocking the vector will take nearly as much time as it would take when calling cout
directly in the main thread.
Question: Is there an alternative to locking/unlocking the vector? Are my worries regarding the locking of the vector misguided? Would you take a whole different approach to solve the problem?
Upvotes: 0
Views: 41
Reputation: 2548
You could use the idea one often sees in "interrupt" programming - send data from the thread to a ring buffer. Then, in another thread, print from the ring buffer. Actually, in the "good old days", one could write a ring buffer without any "atomics" (and can still do on some embedded systems).
But, even with atomics, ring buffers are not hard to write. There is one implementation here: c++ threadsafe ringbuffer implementation (untested, but on the first look seems OK).
Upvotes: 1
Reputation: 490738
Depending on how time-sensitive the task is, I'd probably build up a vector of outputs in the producer thread, then pass the whole vector to the consumer thread (and repeat as needed).
The queue between the two will need to be thread safe, but you can keep the overhead minuscule by passing a vector every, say, 50-100 ms or so. This is still short enough to look like real-time to most observers, but is long enough to keep the overhead of locking far too low to care about in most cases.
Upvotes: 1