0

I wrote a simple program in Python:

from random import random
from threading import Thread
from time import sleep

def write_to_file(i):
    sleep(random())
    with open("test.txt", "a") as f:
        f.write(f"{i}\n")

for i in range(20):
    Thread(target=write_to_file, args=[i]).run()

I'd expect this program to write numbers from 0-19 to test.txt in random order. Instead, the program writes 0-19 in order, and it takes a few seconds to complete, signifying that it executed threads one after the other, in order.

How does this work? Does with open(...) block every other thread from running that also has with open(...) on the same file?

2 Answers 2

1

Don't use the run method, change it to start, the run method is to call the main thread, equivalent to the ordinary function, start will only create a new thread, you wait a few seconds here because you set sleep(random()), you can comment this line:

from threading import Thread

def write_to_file(i):
    with open("test.txt", "a") as f:
        f.write(f"{i}\n")

for i in range(20):
    Thread(target=write_to_file, args=[i]).start()
Sign up to request clarification or add additional context in comments.

Comments

1

Does with open(...) block every other thread from running that also has with open(...) on the same file?

No, it doesn't.

run method of a thread starts and joins the thread which means that it waits for a thread to be joint for every iteration. To make it parallel you must call start instead of run then join all threads at once.

from random import random
from threading import Thread
from time import sleep


def write_to_file(i):
    sleep(random())
    with open("test.txt", "a") as f:
        f.write(f"{i}\n")


threads = []

for i in range(20):
    thread = Thread(target=write_to_file, args=[i])
    thread.start()
    threads.append(thread)

for thread in threads:
    thread.join()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.