Introduction to Python multithreaded programming

Source: Internet
Author: User

Creating Threads

The format is 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 () Start the execution of a thread
Run () Functions that define the functionality of a thread (typically overridden by a quilt class)
Join (Timeout=none) The program hangs until the thread ends, and if timeout is given, it blocks timeout seconds
GetName () Returns the name of the thread
SetName (name) Set the name of the thread
IsAlive () A Boolean flag that indicates whether the thread is still running
Isdaemon () Returns the daemon flag for a thread
Setdaemon (Daemonic) Set the thread's daemon flag to Daemonic (be sure to call before the start () function is called)
Common examples
    • Format
import threadingdef run(*arg, **karg):    pass"default", args = (), kwargs = {})thread.start()
    • Instance
#!/usr/bin/python#coding =utf-8ImportThreading fromTimeImportCtime,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 ()#等待线程结束 forTinchThreads:t.join ()Print "Game Over"

Output

sing start:  (‘raise me up‘,)dance start:  (‘Rup‘,)stopstopgame over

Introduction to Python multithreaded programming

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.