Python multithreaded Programming Simple introduction _python

Source: Internet
Author: User

Creating Threads

Format is as follows

Copy Code code as follows:

Threading. Thread (Group=none, Target=none, Name=none, args= (), kwargs={})

This constructor must be invoked with a keyword pass parameter
-Group Thread groups
-Target Execution method
-Name thread names
-args target-executed tuple parameters
-Kwargs target-executed dictionary parameters

Thread Object function

Function description
Start () execution of the thread
Run () A function that defines the function of a thread (typically overridden by a quilt class)
The Join (Timeout=none) program hangs until the thread finishes, and if timeout is given, the maximum blocking timeout seconds
GetName () returns the name of the thread
SetName (name) sets the name of the thread
IsAlive () Boolean flag indicating whether this thread is still running
Isdaemon () returns the daemon flag of the thread
Setdaemon (daemonic) sets the thread's daemon flag to daemonic (must be called before the start () function is called)

Common examples

Format

Copy Code code as follows:

Import threading

def run (*arg, **karg):
Pass
Thread = Threading. Thread (target = run, name = "Default", args = (), Kwargs = {})
Thread.Start ()


Instance
Copy Code code 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 = []

#创建线程对象
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)

#开始线程
T1.start ()
T2.start ()

#等待线程结束
For T in Threads:
T.join ()

Print "Game Over"


Output
Copy Code code as follows:

Sing start: (' Raise Me Up ',)
Dance Start: (' Rup ',)
Sing stop
Dance Stop
Game Over

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.