Printf in multithreading context
Hi,
I'm writing a program which use multiple threads. Now, I'd need to print for each thread some info. Basically, each thread loads some data and I'd want to print something like: Code:
printf("Thread %d -> Data (%d/%d)", thread_num, cur_data, tot_data); Carriage return usage should be ok but, in this case, each thread overwrites the line getting a non-wanted behaviour. How could I achieve this goal ? Regards |
Have each thread write an entry to an array. Print the entire array.
Ed |
Use ANSI sequences to move the cursor to specific rows.
|
I definitely prefer @EdGr's suggestion. Very specifically, here's what I would do:
|
Actually, I already thought a new thread but I was wondering whether a simple Ansi escape sequence can resolve the problem. Anyway the latter requires a mutex to properly work and I'd want to avoid because will cause a little bit slowing about threads parallelism. The new thread will have to simply composite an unique string with the data which are already in memory and print it with carriage return.
Thanks all for feedbacks. Mark as solved. |
If "every thread, independently," tries to perform I/O, the fully-asynchronous nature of "multitasking" inevitably results in visual chaos. After all, the thread or process could be pre-empted in the middle of trying to send a character sequence. It simply doesn't work.
In fact, this idea works generally. When "many threads or processes" need to read or write from a single physical resource, such as a disk file, the most-reliable method is to dedicate one thread or process, fed by (or, supplying) queues of some sort, to the task of "actually doing it." |
yes, with other words (and in general): you need only one worker thread and all the other threads can collect and put the data into a common area/variable/array. This should be used in every case when the given "work" is not thread safe (like displaying those messages).
|
Quote:
Honestly, the reason I didn’t spell this out is because I assumed I didn’t need to. |
Quote:
|
Quote:
|
All times are GMT -5. The time now is 10:42 AM. |