Bob
Bob

Reputation: 35

Python multi threads are not executed in parallel

I have executed the following Python code.

from time import sleep
from threading import *

class myclass1(Thread):
    def run(self):
        for i in range(5):
            print("aaa")
            sleep(1)

class myclass2(Thread):
    def run(self):
        for i in range(5):
            print("bbb")
            sleep(1)

mc1 = myclass1()
mc2 = myclass2()

mc1.start()
mc2.start()

The output contains "aaabbb".

aaa
bbb
aaabbb

aaa
bbb
aaa
bbb
aaa
bbb

I don't understand why the result contains "aaabbb". Does this means print("aaabbb") was executed in one thread?

Upvotes: 2

Views: 57

Answers (1)

blhsing
blhsing

Reputation: 106598

The standard output is writeable to both threads at any time so if one thread writes a line to the standard output in the middle of another thread writing a line to the standard output, you would then see the lines from the two threads getting mixed up.

To avoid such a race condition, you can use a threading.Lock to ensure that there is always only one thread at a time that can call print, and that the other thread would be blocked until the lock is released after print has returned:

from time import sleep
from threading import *

class myclass(Thread):
    def __init__(self, name, lock, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.name = name
        self.lock = lock
    def run(self):
        for i in range(5):
            with self.lock:
                print(self.name)
            sleep(1)

lock=Lock()
mc1 = myclass('aaa', lock)
mc2 = myclass('bbb', lock)

mc1.start()
mc2.start()

Upvotes: 1

Related Questions