Describing Thread(group, target, name, args)
- The
Threadobject creates a newThreadinstance - The
targetis a callable object (e.g. function) - It is invoked by the
run()method - Typically, we use the
start()method to invoke therun()method - By default,
targetisNone - Meaning, nothing is called
- The
nameis the thread name - By default, a unique name of the form
Thread-Nis created - The
argsis a tuple of arguments passed to thetargetfunction
Example of Thread
# sleepy.py
>>> import logging
>>> import threading as t
>>> import time
>>> def sleep_thread(msg):
... print('thread started')
... print(msg)
... time.sleep(2)
... print('thread done')
>>> if __name__ == "__main__":
... print('main started')
... msg = 'i am sleepy'
... thd = t.Thread(target=sleep_thread, args=(msg,))
... print('main created thread')
... thd.start()
... print('main started thread')
... print('main done')# !/bin/sh
$ python3 sleepy.py
main started
main created thread
thread started
i am sleepy
main started thread
main done
thread doneReferences
Previous
Next