Just started python the other day, new to the entire concept of multi-threading. I am having trouble with writing to a file while multi-threading. If I do it the regular way, it will constantly overwrite what’s being written.
What is the proper way to write to a file while using say 5 threads?
The best way as to not reduce performance is to use a queue between all threads, each thread would enque an item while a main thread would simply deque an item and write it to a file, the queue is thread safe and blocking when its empty, or better yet if possible, simply return all the values from the 5 threads and then write it to the file, IO tends to be one of the more expensive operations we can do, so its best to limit it as much as we can.
Also note that threads in python don’t take advantage of multiple core, cause of the GIL instead use multiprocessing if you want to leverage multiple processing engines.
here is a quick example:
and the contents of
test.txt: