1

I'm trying to create an instance of a Thread type class called A within the class B that's in the same file.

I tried some combinations x = A(i), x = A.A(i), x = A.__init(i) and so on...

from threading import Thread

class A(Thread):
    def __init__(self, i)
        Thread.__init__(self)
        self.i = i

    def run(self):
        print('foo')

class B()
    def __init__(self):
        x = #instance of A ?
        x.start()

if __name__ == '__main__':
    B() # Here I call the class B that should start the thread of A

I need to call the class. And not a method inside the class. Because I want then to call the x.start() method to start the thread.

Andrew Carter
  • 371
  • 1
  • 4
Jeflopo
  • 2,192
  • 4
  • 34
  • 46

1 Answers1

0

You can call x.start() like you show. Just make sure to call x.join() from B.__init__ -- this is the main thread. In general, you want the main thread to 'wait' or 'join' on all sub threads. Here is a working example:

>>> from threading import Thread
>>> import time
>>>
>>> class A(Thread):
...
...    def __init__(self, i):
...        Thread.__init__(self)
...        self._index = i
...        
...    def run(self):
...        time.sleep(0.010)
...        for i in range(self._index):
...            print('Thread A running with index i: %d' % i)
...            time.sleep(0.100)
...            
>>>
>>> class B(object):
...    
...    def __init__(self, index):
...        x = A(i=index)
...        print ('starting thread.')
...        x.start()
...        print('waiting ...')
...        x.join()
...        print('Thread is complete.')
...        
>>> if __name__ == '__main__':
...    B(10) # Here I call the class B that should start the thread of A
starting thread.
waiting ...
Thread A running with index i: 0
Thread A running with index i: 1
Thread A running with index i: 2
Thread A running with index i: 3
Thread A running with index i: 4
Thread A running with index i: 5
Thread A running with index i: 6
Thread A running with index i: 7
Thread A running with index i: 8
Thread A running with index i: 9
Thread is complete.

Last note, there is no reason that A.__init__ can't call start() on itself (instead of B.__init__ doing it) -- that's just a matter of style. The only really key thing is that the main thread should in best practice wait or join on all subthreads -- if you don't do this you can get strange behavior in certain applications as the main thread exits before sub-threads. See this:

for more.

Community
  • 1
  • 1
Andrew Carter
  • 371
  • 1
  • 4
  • It's weird... I get `NameError: name 'A' is not defined` in mine... But If I copy your code in another file it works. Names are exact... I'm trying to find whats wrong. Maybe class declaration order in the code its important ??? – Jeflopo Mar 04 '15 at 16:00
  • LOL... The problem was the order of class declarations. I declared the `Thread` class after the other. Switched them and It works now ! Thank you ! – Jeflopo Mar 04 '15 at 16:05