I am having trouble understanding how to get simple multi-threading to work in python. Here is a simple script I have written in python that should simultaneously write to two different files:
from threading import Thread import time def function(file): with open(file, 'w') as f: i = 0 while i < 10: print(file + ' printing ' + str(i)) f.write(str(i) + '\n') time.sleep(0.4) i += 1 if __name__ == '__main__': thr1 = Thread(target=function('thr1.txt')) thr2 = Thread(target=function('thr2.txt')) thr1.start() thr2.start() The output of this code being run suggests that these functions are not being executed in parallel but instead one after the other:
thr1.txt printing 0 thr1.txt printing 1 thr1.txt printing 2 thr1.txt printing 3 thr1.txt printing 4 thr1.txt printing 5 thr1.txt printing 6 thr1.txt printing 7 thr1.txt printing 8 thr1.txt printing 9 thr2.txt printing 0 thr2.txt printing 1 thr2.txt printing 2 thr2.txt printing 3 thr2.txt printing 4 thr2.txt printing 5 thr2.txt printing 6 thr2.txt printing 7 thr2.txt printing 8 thr2.txt printing 9 Process finished with exit code 0 Have I misunderstood the basics of multithreading functions in python because from the resources I have looked at this appears to be the way it is done?