Python note 7-multithreaded threading function

Source: Internet
Author: User

Objective

1.python Environment 2.7
2.threading module System comes with

Single Thread

1. The usual code is executed in order, like eating hot pot and humming the two behavioral events, defined as two functions, the implementation of the time is to eat hot pot and then hum a tune, this is a single-threaded behavior.

#Coding:utf-8Import Timedefchi ():Print("%s Eat hotpot start:"%time.ctime ()) Time.sleep (1)    Print("%s Eat pot End--"%time.ctime ())defHeng ():Print("%s humming a ditty to begin with:"%time.ctime ()) Time.sleep (1)    Print("%s Humming A ditty end--"%time.ctime ())if __name__=="__main__": Chi () Heng () Thu Jan11 16:32:37 2018eat hotpot start: Thu Jan11 16:32:38 2018 Eat hotpot End--Thu Jan11 16:32:38 2018humming a ditty start: Thu Jan11 16:32:39 2018 Humming a tune to the end--

2. In life we can eat hot pot while humming a song, then how to achieve this in the code of the different events at the same time? This is the next Python multithreading

Multithreading threading

1.Python provides support for threads through two standard library thread and threading. The thread provides a low-level, primitive thread, and a simple lock. The threading module encapsulates a number of common methods that beginners can directly learn from this module.

There are two ways to use threads in 2.Python: Functions or classes to wrap thread objects

3.threading. Thread inside several parameters introduced:

class Thread(_Verbose)      __init__(self, group=None, target=None, name=None, args=(), kwargs=None, verbose=None) *group*:group参数必须为空,参数group是预留的,用于将来扩展;   参数args和kwargs分别表示调用target时的参数列表和关键字参数。 *target*: 参数target是一个可调用对象(也称为活动[activity]),在线程启动后执行 *name*: 参数name是线程的名字。默认值为“Thread-N“,N是一个数字。 *args*:传递给线程函数target的参数,他必须是个tuple类型. *kwargs*:kwargs表示关键字参数。字典类型 {}. 
function type

1. Let's look at a simple case, this is the execution function, the function without parameters

#Coding:utf-8ImportThreadingImport Timedefchi ():Print("The%s begins with a hotpot meal:"%time.ctime ()) Time.sleep (1)    Print("%s eating hotpot: Mutton"%time.ctime ()) Time.sleep (1)    Print("%s eating hotpot: Shabushabu"%time.ctime ()) Time.sleep (1)    Print("%s eating hotpot: Gong pills"%time.ctime ()) Time.sleep (1)    Print("%s eat hotpot end! "%time.ctime ())defTing ():Print("%s humming a ditty 1! "%time.ctime ()) Time.sleep (2)    Print("%s humming a ditty 2! "%time.ctime ()) Time.sleep (2)    Print("%s humming a ditty 3! "%time.ctime ()) Time.sleep (2)    Print("%s humming a ditty 4! "%time.ctime ()) Time.sleep (2)    Print("%s humming a ditty 5! "%time.ctime ()) Time.sleep (2)#creating an array of threadsThreads = []#creates a thread T1 and adds it to the thread arrayT1 = Threading. Thread (target=chi) threads.append (t1)#creates a thread T2 and adds it to the thread arrayT2 = Threading. Thread (target=Ting) threads.append (T2)if __name__=='__main__':    #Start Thread     forTinchThreads:t.start ()

Operation Result:
Thu Jan 11 16:35:50 2018 Eat hotpot Start:
Thu Jan 11 16:35:50 2018 Humming a ditty 1!
Thu Jan 11 16:35:51 2018 eating hotpot: Mutton
Thu Jan 11 16:35:52 2018 Humming a ditty 2! Thu Jan 11 16:35:52 2018 Eating hotpot: Shabushabu

Thu Jan 11 16:35:53 2018 Eating hotpot: Gong pills
Thu Jan 11 16:35:54 2018 Humming a ditty 3! Thu Jan 11 16:35:54 2018 Eat Hotpot end!

Thu Jan 11 16:35:56 2018 Humming a ditty 4!
Thu Jan 11 16:35:58 2018 Humming a ditty 5!

2. Using the args to send a tuple type with the parameter (the parameter is added a comma "," otherwise will be an error)

#Coding:utf-8ImportThreadingImport TimedefChi (threadname,name):Print("%s starts with%s:"%(Time.ctime (), threadname))Print("%s eating hotpot: Mutton"%time.ctime ()) Time.sleep (1) Time.sleep (1)    Print("%s eating hotpot: Shabushabu"%time.ctime ()) Time.sleep (1)    Print("%s eating hotpot: Gong pills"%time.ctime ()) Time.sleep (1)    Print("%s ends at eating%s--"%(Time.ctime (), threadname))Print("%s Run end! "%name)defTing (threadname):Print("%s humming the%s1! "%(Time.ctime (), ThreadName)) Time.sleep (2)    Print("%s humming a ditty 2! "%time.ctime ()) Time.sleep (2)    Print("%s humming a ditty 3! "%time.ctime ()) Time.sleep (2)    Print("%s humming a ditty 4! "%time.ctime ()) Time.sleep (2)    Print("%s humming a ditty 5! "%time.ctime ()) Time.sleep (2)#creating an array of threadsThreads = []#creates a thread T1 and adds it to the thread array#T1 = Threading. Thread (Target=chi, args= ("hotpot", "Eat Hotpot",))#Pass Kwargs ParametersT1 = Threading. Thread (Target=chi, kwargs={"ThreadName":"Hot Pot","name":"Eat Hot pot"}) threads.append (t1)#creates a thread T2 and adds it to the thread arrayT2 = Threading. Thread (target=ting,args= ("Ditty",)) Threads.append (T2)if __name__=='__main__':    #Start Thread     forTinchThreads:t.start ()

3. Or use Kwargs to pass the dictionary {} type

# 创建线程t1,并添加到线程数组# t1 = threading.Thread(target=chi, args=("火锅","吃火锅",))# 传kwargs参数t1 = threading.Thread(target=chi, kwargs={"threadName":"火锅","name":"吃火锅"})

Encapsulates the invocation of classes and methods in the next chapter

Python note 7-multithreaded threading function

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.