Shammer's Philosophy

My private adversaria

Using Python Thread

Python supports thread execution. This is so similar with Java.

  • Inherit Thread class and override run method
  • Mapping some function to Thread and start that Thread

Inherit Thread class

#!/usr/bin/env python
import threading

class MyThread(threading.Thread):
    def __init__(self, name):
        super(MyThread, self).__init__()
        self.name = name
        
    def run(self):
        print 'Hello, ' + self.name

if __name__ == '__main__':
    mythread = MyThread('Taro')
    mythread.start()

Mapping some function to Thread

#!/usr/bin/env python
import threading

def running(name):
    print 'Hello, ' + name

if __name__ == '__main__':
    mythread = threading.Thread(target=running, args=('Taro',))
    mythread.start()

The parameter of Thread "args" requires last ",". If this "," is not exists, the following error happened.

Traceback (most recent call last):
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 810, in __bootstrap_inner
    self.run()
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 763, in run
    self.__target(*self.__args, **self.__kwargs)
TypeError: running() takes exactly 1 argument (4 given)