Python multithreaded Programming Simple introduction

Source: Internet
Author: User
Creating Threads

The format is as follows
Copy the Code code as follows:


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


This constructor must be called with the keyword argument
-Group Thread groups
-Target Execution method
-Name thread names
-Tuple parameters executed by the args target
-Dictionary parameters executed by Kwargs target

Thread Object functions

Function description
Start () starts the execution of the thread
Run () A function that defines the functionality of the thread (typically overridden by a quilt class)
The Join (Timeout=none) program hangs until the thread ends, and if timeout is given, it blocks timeout seconds
GetName () returns the name of the thread
SetName (name) sets the name of the thread
The IsAlive () Boolean flag that indicates 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 (be sure to call before the start () function is called)

Common examples

Format
Copy the Code code as follows:


Import threading

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


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

#创建线程对象
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 CodeThe code is as follows:


Sing start: (' Raise Me Up ',)
Dance Start: (' Rup ',)
Sing stop
Dance Stop
Game Over
  • 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.