Python note 7-multithreaded threading

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 timedef chi():    print("%s 吃火锅开始:" % time.ctime())    time.sleep(1)    print("%s 吃火锅结束--" % time.ctime())def heng():    print("%s 哼着小曲开始:" % time.ctime())    time.sleep(1)    print("%s 哼着小曲结束--" % time.ctime())if __name__ == "__main__":    chi()    heng()

Thu Jan 11 16:32:37 2018 Eat hotpot Start:
Thu Jan 11 16:32:38 2018 Eat hotpot End--
Thu Jan 11 16:32:38 2018 Humming a ditty begins:
Thu Jan 11 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-8import threadingimport timedef chi (): Print ("%s starts with hotpot:"% time.ctime ()) Time.sleep (1) p Rint ("%s eats hot pot: Mutton"% time.ctime ()) time.sleep (1) print ("%s eating hotpot: shabu beef"% time.ctime ()) time.sleep (1) print ("%s eat Fire pot: Gong pill "% time.ctime ()) time.sleep (1) print ("%s Eat pot end! "% Time.ctime ()) def ting (): 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) # Create thread array threads = []# Create thread t1 and add to thread array t1 = Threading. Thread (Target=chi) threads.append (T1) # creates Threads T2 and adds to the thread array t2 = Threading. Thread (target=ting) threads.append (t2) If __name__ = = ' __main__ ': # boot thread for T in Threads: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-8import Threadingimport timedef chi (threadname,name): Print ("%s starts with%s:"% (Time.ctime (), threadname)) p Rint ("%s eats hot pot: Mutton"% time.ctime ()) Time.sleep (1) time.sleep (1) print ("%s eating hotpot: shabu beef"% time.ctime ()) Time.sleep (  1) Print ("%s eats hotpot: Gong pill"% time.ctime ()) time.sleep (1) print ("%s ate%s end-"% (Time.ctime (), threadname) print ("%s Run the end! "%name) def Ting (threadname): Print ("%s humming%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) # Create thread array threads = []# Create thread t1 and add to thread array # t1 = Threading. Thread (Target=chi, args= ("hotpot", "Eat Hotpot",)) # Kwargs parameter T1 = Threading. Thread (Target=chi, kwargs={"ThreadName": "Hotpot", "name": "Eat Hotpot"}) threads.append (t1) # Create thread T2 and add to the thread array t2 = Threading.    Thread (target=ting,args= ("ditty")) Threads.append (t2) If __name__ = = ' __main__ ': # Start threadFor T in Threads: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

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.