Here I have a code containing a simple class printing something. I want to multithread it.
import threading
import time
import random
class Useless:
def __init__(self, numb):
self.numb = numb
def printing(self):
time.sleep(random.uniform(0.05, 0.09))
print(f'number {self.numb} is being printed God knows what for...')
def main_loop(self):
for _ in range(5):
self.printing()
obj_1 = Useless(1)
obj_2 = Useless(2)
proc_1 = threading.Thread(target=obj_1.main_loop, args=())
proc_2 = threading.Thread(target=obj_2.main_loop, args=())
proc_1.start()
proc_2.start()
The number of threads is arbitrary, so I can create more proc_. This is a key requirement!
But sometimes I receive a weird printing results like this:
number 2 is being printed God knows what for...number 1 is being printed God knows what for...
number 1 is being printed God knows what for...
number 2 is being printed God knows what for...
number 1 is being printed God knows what for...
number 2 is being printed God knows what for...
number 1 is being printed God knows what for...
number 2 is being printed God knows what for...
number 1 is being printed God knows what for...
number 2 is being printed God knows what for...
Process finished with exit code 0
You see sometimes some printed messages mix together and printed in one line but I would like them to be separate.
Probably subprocess pipe can help with it but I don't know how to implement it here. Probably Asyncio can solve it. So I want threads to be executed simultaneously (almost simultaneously within one core) but to have printed messages separated.
CodePudding user response:
Although there is no guarantees (this is highly OS specific), you can hardly send newline to stdout instead of python handling this
def printing(self):
print(f'number {self.numb} is being printed God knows what for...\n', end='')
But I still do not recommend using this approach as it does not solve problem. Much appropriate way is to use some buffers and flush them synchronously
CodePudding user response:
just pass the flush
keyword args into print function, and no print will be concatenated
print("Hello world", flush=True)