Click here to Skip to main content
14,454,836 members
Rate this:
Please Sign up or sign in to vote.
I am looking for an example which creates multiple threads and all threads are writing the data into single file. It should be in continues loop. If file size are 1 KB then stop the program.

What I have tried:

I have tried creating multiple threads but I am not able to write data in a single file from all threads.
Updated 30-Aug-18 15:30pm
KarstenK 31-Aug-18 2:25am
Sounds a bit like a design flaw that different thread are writing into one file. Maybe you create another file writer thread. ;-)
Rate this:
Please Sign up or sign in to vote.

Solution 1

In my opinion, having all the threads write to the same file is unnecessarily complicated. I would make a 1KB buffer and a custom routine to write your data into it with a mutex or critical section to control access. Your threads can write into the buffer until its full at which time the threads terminate. The primary thread could be signaled when that happens and it could then write the data to the file and terminate the process. This seems pretty simple to me as long as you know how to manage threads.
Rate this:
Please Sign up or sign in to vote.

Solution 2

You need to have One extra threads.
* Writer, that writes data into file.
* You need to have Queue, Worker thread will push data into queue
* Both Queue will have to be thread safe.
* Each worker thread will generate it's own data and push to a queue.
* Writer thread will pop data from Queue and write into files.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100