How to prevent class contructor from blocking other threads?

Question:

I am new to threading, so this question might be too basic.
I have two classes A and B. If I put their respective instances and methods in two threads as below:

from threading import Thread
from time import sleep

class A:
    def __init__(self):
        sleep(10)
        print('class A __init__ awake')

    def method_a(self):
        sleep(10)
        print('method_a awake')

class B:
    def __init__(self):
        sleep(1)
        print('class B __init__ awake')

    def method_b(self):
        sleep(5)
        print('method_b awake')


thread_a = Thread(target=A().method_a)
thread_b = Thread(target=B().method_b)
thread_a.start()
thread_b.start()

my expected result would be:

class B __init__ awake
method_b awake
class A __init__ awake
method_a awake

but I am getting:

class A __init__ awake
class B __init__ awake
method_b awake
method_a awake

What am I doing wrong? Is it the way I am passing my methods to Thread instance or something more fundamental?
Thanks.

Asked By: sierra_papa

||

Answers:

the most straight forward way to do it is to wrap the object creation and function execution in a function that does both, that will be executed entirely in another thread.

thread_a = Thread(target=lambda: A().method_a())
thread_b = Thread(target=lambda: B().method_b())
Answered By: Ahmed AEK