This article introduces Python multi-Thread programming. This article describes how to create a Thread, Thread object function, and common examples. For more information, see
Create thread
The format is as follows:
The code is as follows:
Threading. Thread (group = None, target = None, name = None, args = (), kwargs = {})
This constructor must be called by passing parameters with keywords.
-Group Thread group
-Target execution method
-Name: thread name
-Tuples executed by args target
-Dictionary parameters executed by kwargs target
Thread object functions
Function description
Start () starts Thread Execution
Run () is a function that defines the functions of a thread (usually overwritten by the quilt class)
The join (timeout = None) program is suspended until the thread ends. if timeout is given, a maximum of timeout seconds can be blocked.
GetName () returns the thread name
SetName (name) sets the thread name
The isAlive () Boolean flag indicates whether the thread is still running.
IsDaemon () returns the daemon flag of the thread
SetDaemon (daemonic) sets the daemon flag of a thread to daemonic (must be called before the start () function is called)
Common examples
Format
The code is as follows:
Import threading
Def run (* arg, ** karg ):
Pass
Thread = threading. Thread (target = run, name = "default", args = (), kwargs = {})
Thread. start ()
Instance
The code is as follows:
#! /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 = ('rule ',))
Threads. append (t2)
# Start thread
T1.start ()
T2.start ()
# Waiting for the thread to end
For t in threads:
T. join ()
Print "game over"
Output
The code is as follows:
Sing start: ('raise me up ',)
Dance start: ('rule ',)
Sing stop
Dance stop
Game over