Python multithreaded programming

Source: Internet
Author: User

A) Thread Foundation

1. Create Thread:

The thread module provides a start_new_thread function to create a thread. The Start_new_thread function can also be manipulated after it has been successfully created.

Its function prototype:

Start_new_thread (Function,atgs[,kwargs])

The meaning of its parameters is as follows:

Function: The name of the functions running in the thread

Args: A list of tuples in the form of a tuple.

Kwargs: Optional number of references, specifying the number of references in the form of a dictionary

Method One: Create a new thread by using a function in the thread module.

>>> Import thread>>> def run (n): For I in range (n):p rint i>>> Thread.start_new_thread (run , (4,)) #注意第二个參数一定要是元组的形式538401 >>> 23keyboardinterrupt>>> Thread.start_new_thread (Run, (2,)) 178401>>> Thread.start_new_thread (Run, (), {' N ': 4}) 397201>>> 23thread.start_new_thread (Run, (), {' N ': 3}) 324801>>> 2

Method Two: By inheriting threading. Thread Creation Threads

>>> Import threading>>> class Mythread (threading. Thread):d EF __init__ (self,num): Threading. Thread.__init__ (self) self.num = Numdef Run (self): #重载run方法print ' I am ', self.num>>> t1 = mythread (1 ) >>> t2 = mythread (2) >>> t3 = mythread (3) >>> T1.start () #执行线程t1I am>>> 1t2. Start () I am>>> 2t3.start () I am>>> 3

Method Three: Use threading. Thread executes the function directly in the thread.

Import threading>>> def run (x, y): For I in range (x, y):p rint i>>> t1 = Threading. Thread (target=run,args= (15,20)) #直接使用Thread附加函数args为函数參数 >>> T1.start () 15>>> 16171819

II) regular usage in the thread object:

1, IsAlive Method:

>>> Import threading>>> Import time>>> class Mythread (threading. Thread):d EF __init__ (self,id): Threading. Thread.__init__ (self) self.id = Iddef Run (self): Time.sleep (5) #休眠5秒print self.id>>> t = mythread (1) >>> ; def func (): T.start () print t.isalive () #打印线程状态 >>> func () true>>> 1

2. Join method:

Prototype: Join ([timeout])

Timeout: The maximum length of time that the thread executes, with an optional number of parameters

Import threading>>> Import time #导入time模块 >>> class Mythread (threading. Thread):d EF __init__ (self,id): Threading. Thread.__init__ (self) self.id = Iddef Run (self): x = 0time.sleep (+) print self.id>>> def func (): T.start () for I in Range (5):p rint i>>> t = Mythread (2) >>> func () 01234>>> 2def func (): T.start () T.join () for I in Range (5):p rint i>>> t = Mythread (3) >>> func () 301234>>>

3. Thread Name:

>>> Import threading>>> class Mythread (threading. Thread):d EF __init__ (self,threadname): Threading. Thread.__init__ (Self,name=threadname) def run (self):p rint self.getname () >>> >>> t1 = mythread (' t1 ') >>> T1.start () t1>>>

4. Setdaemon method

There is a main thread in the execution of the script, assuming that the main thread has created another child thread, and when the main thread exits, it verifies that the child thread is complete. Assuming that the child thread is not complete, the main thread exits after waiting for the child thread to complete.

When the main thread exits, the Setdaemon method of the thread object can be used to set it up, regardless of whether the child thread is finished with the main thread.

III) thread synchronization

1. Simple thread Synchronization

Using the thread object's lock and Rlock enables simple thread synchronization. For hypothetical data that requires only one thread at a time, the operation can be placed between the Acquire method and the release method. Such as:

#-*-Coding:utf-8-*-import threadingimport timeclass mythread (threading. Thread):d EF __init__ (self,threadname): Threading. thread.__init__ (Self,name = threadname) def run (self): Global x #设置全局变量 #lock.acquire () #调用lock的acqui Re method for I in range (3): x = x + 1time.sleep (2) print x#lock.release () #调用lock的release方法 #lock = Threading. Rlock () #生成Rlock对象t1 = []for i in range: t = mythread (str (i)) T1.append (t) x = 0 #将全局变量的值设为0for I in T1:i.start () e:/study/python/workspace>xianchengtongbu.py36912151821242730

Suppose Lock.acquire () and Lock.release (), lock = Threading. Lock () Saves the execution script after deletion, and the result will be output of 10 30. 30 is the last value of x, because x is a global variable, and each thread enters hibernation after its operation, and the Python interpreter executes the other thread instead of the value of x when it sleeps. When all threads hibernate, the value of x has been changed by all lines in order to 30, so the output is all 30.

2. Use condition variables to keep threads in sync.

Python's condition object provides support for replication thread synchronization. Use the Condition object to process data after certain events have been triggered. In addition to the method of acquire and release, the condition object is used for conditional processing, such as Wait method, notify method, Notifyall method, etc.

#-*-Coding:utf-8-*-import threadingclass Producer (threading. Thread):d EF __init__ (self,threadname): Threading. thread.__init__ (Self,name = threadname) def run (self): global Xcon.acquire () if x = = 1000000:con.wait () #passelse: For I in Range (1000000): x = x + 1con.notify () print xcon.release () class Consumer (threading. Thread):d EF __init__ (self,threadname): Threading. thread.__init__ (Self,name = threadname) def run (self): Global x Con.acquire () if x = = 0:con.wait () #passelse: For I in range (1 000000): x = x-1con.notify () print x con.release () con = threading. Condition () x = 0p = Producer (' Producer ') c = Consumer (' Consumer ') P.start () C.start () P.join () c.join () print xe:/study/ python/workspace>xianchengtongbu2.py100000000

Inter-thread communication:

The event object is used to communicate with each other between threads. He provides set-up signals, clear macros, waits, and so on to enable communication between threads.

1, set the signal. After the event object uses the set () method, the IsSet () method returns True.

2, clear the signal. After you use the clear () method of the event object, the IsSet () method returns FALSE.

3, wait. When the internal signal flag of the event object is false, the wait () method waits until it is true to return. You can also pass the number of parameters to wait, setting the maximum waiting time.

#-*-Coding:utf-8-*-import threadingclass mythread (threading. Thread):d EF __init__ (self,threadname): Threading. thread.__init__ (Self,name = threadname) def run (self): global eventif Event.isset (): Event.clear () event.wait () # Returns print Self.getname () else:print self.getname () event.set () event = threading When the event is marked. Event () event.set () T1 = []for i in Range (Ten): t = mythread (str (i)) T1.append (t) for I in T1:i.start ()

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.