A brief introduction to Python multithreaded programming

  • 2020-05-09 18:45:52
  • OfStack

Create a thread

Format is as follows


threading.Thread(group=None, target=None, name=None, args=(), kwargs={})

The constructor must be called with a keyword
- group thread group
-target execute method
-name thread name
-tuple parameter executed by args target
-dictionary parameter that kwargs target executes

Thread object functions

The function   describes
start()   starts the execution of the thread
run()   functions that define the functionality of threads (1 is usually subclassed)
join(timeout=None)   hangs until the thread ends; If an timeout is given, it blocks timeout for at most seconds
getName()   returns the name of the thread
setName(name)   sets the name of the thread
isAlive()   Boolean flag to indicate whether the thread is still running
isDaemon()   returns the daemon flag of the thread
setDaemon(daemonic)   sets the daemon flag of the thread to daemonic(1 must be called before the start() function is called)

Commonly used sample

format


import threading def run(*arg, **karg):
    pass
thread = threading.Thread(target = run, name = "default", args = (), kwargs = {})
thread.start()

The instance

#!/usr/bin/python
#coding=utf-8 import threading
from time import ctime,sleep def sing(*arg):
    print "sing start: ", arg
    sleep(1)
    print "sing stop"
def dance(*arg):
    print "dance start: ", arg
    sleep(1)
    print "dance stop" threads = [] # Create a thread object
t1 = threading.Thread(target = sing, name = 'singThread', args = ('raise me up',))
threads.append(t1) t2 = threading.Thread(target = dance, name = 'danceThread', args = ('Rup',))
threads.append(t2) # To start a thread
t1.start()
t2.start() # Waiting for the thread to end
for t in threads:
    t.join() print "game over"

The output

sing start:  ('raise me up',)
dance start:  ('Rup',)
sing stop
dance stop
game over


Related articles: