Details of Python multi-thread instances and python instances

Source: Internet
Author: User

Details of Python multi-thread instances and python instances

Detailed description of Python multi-thread instances

1) thread Basics

1. Creation thread:

The thread module provides the start_new_thread function to create a thread. After the start_new_thread function is successfully created, you can perform operations on it.
Its function prototype:

  start_new_thread(function,atgs[,kwargs])

The parameter meanings are as follows:

Function: name of the function executed in the thread
Args: list of parameters in the format of tuples.
Kwargs: optional parameter, which is specified in dictionary form

Method 1: Use the functions in the thread module to create a new thread.

>>> Import thread >>> def run (n): for I in range (n): print I >>> thread. start_new_thread (run, (4,) # note that the second parameter must be in the format of 53840 1 >>> 2 3 KeyboardInterrupt >>> thread. start_new_thread (run, (2,) 17840 1 >>> thread. start_new_thread (run, (), {'N': 4}) 39720 1 >>> 2 3 thread. start_new_thread (run, (), {'N': 3}) 32480 1 >>> 2

Method 2: Create a Thread by inheriting threading. Thread

>>> Import threading >>> class mythread (threading. thread): def _ init _ (self, num): threading. thread. _ init _ (self) self. num = num def run (self): # reload the run method print 'I am', self. num >>> t1 = mythread (1) >>> t2 = mythread (2) >>> t3 = mythread (3) >>> t1.start () # Run thread t1 I am >>> 1 t2.start () I am >>> 2 t3.start () I am >>> 3

Method 3: Use threading. Thread to run functions directly in the Thread.

Import threading >>> def run (x, y): for I in range (x, y): print I >>> t1 = threading. thread (target = run, args = (15, 20) # directly use the Thread appended function args as the function parameter >>> t1.start () 15 >>> 16 17 18 19

2) common methods in Thread objects:

1. isAlive method:

>>> Import threading >>> import time >>> class mythread (threading. thread): def _ init _ (self, id): threading. thread. _ init _ (self) self. id = id def run (self): time. sleep (5) # sleep for 5 seconds print self. id >>> t = mythread (1) >>> def func (): t. start () print t. isAlive () # print the thread status >>> func () True >>> 1

2. join method:

Prototype: join ([timeout])

Timeout: optional parameter. Maximum thread running time

Import threading >>> import time # import time module >>> class Mythread (threading. thread): def _ init _ (self, id): threading. thread. _ init _ (self) self. id = id def run (self): x = 0 time. sleep (20) print self. id >>> def func (): t. start () for I in range (5): print I >>> t = Mythread (2) >>> func () 0 1 2 3 4> 2 def func (): t. start () t. join () for I in range (5): print I >>> t = Mythread (3) >>> func () 3 0 1 2 3 4 >>>

3. Thread Name:

>>> import threading >>> class mythread(threading.Thread):   def __init__(self,threadname):     threading.Thread.__init__(self,name=threadname)   def run(self):     print self.getName()       >>>  >>> t1 = mythread('t1') >>> t1.start() t1 >>>  

4. setDaemon Method

There is a main thread in the script running process. If the main thread creates another sub-thread, when the main thread exits, it checks whether the Sub-thread is complete. If the sub-thread is not completed, the main thread will exit after the sub-thread is completed.

When you need to exit the main Thread, you can use the setDaemon method of the Thread object to set whether or not the non-pipe Thread is completed and exits with the main Thread.

3) thread synchronization

1. Simple Thread Synchronization

The Lock and RLock of the Thread object can be used for simple Thread synchronization. If you need to operate data with only one thread at a time, you can place the operation process between the acquire method and the release method. For example:

#-*-Coding: UTF-8-*-import threading import time class mythread (threading. thread): def _ init _ (self, threadname): threading. thread. _ init _ (self, name = threadname) def run (self): global x # set the global variable # lock. acquire () # Call lock's acquire Method for I in range (3): x = x + 1 time. sleep (2) print x # lock. release () # Call the lock release method # lock = threading. RLock () # generate Rlock object t1 = [] for I in range (10): t = mythread (str (I) t1.append (t) x = 0 # set the global variable value to 0 for I in t1: I. start () E: /study/<a href = "http://lib.csdn.net/base/python" rel = "external nofollow" class = 'replace _ word' title = "Python knowledge base" target = '_ blank' style = 'color: # df3434; font-weight: bold; '> Python </a>/workspace> xianchengtongbu. py 3 6 9 12 15 18 21 24 27 30

If you delete lock. acquire () and lock. release (), lock = threading. Lock () and save the running script, the output result is 10 to 30. 30 is the final value of x. Since x is a global variable, each thread enters the sleep state after performing operations on it, the Python interpreter executes other threads but increases the value of x. After All threads sleep, the value of x has been changed to 30 by the wired mode, so the output is all 30.

2. Use conditional variables to keep the thread synchronized.

Python's Condition object provides support for replication thread synchronization. The Condition object can be used to process data only after some events are triggered. In addition to the acquire and release methods, the Condition object also has the wait, y, and policyall methods for Condition processing.

# -*- coding:utf-8 -*- import threading class Producer(threading.Thread):   def __init__(self,threadname):     threading.Thread.__init__(self,name = threadname)   def run(self):     global x     con.acquire()     if x == 1000000:       con.wait()     #  pass     else:       for i in range(1000000):         x = x + 1       con.notify()     print x     con.release() class Consumer(threading.Thread):   def __init__(self,threadname):     threading.Thread.__init__(self,name = threadname)   def run(self):     global x      con.acquire()     if x == 0:       con.wait()       #pass     else:       for i in range(1000000):         x = x - 1       con.notify()     print x      con.release() con = threading.Condition() x = 0 p = Producer('Producer') c = Consumer('Consumer') p.start() c.start() p.join() c.join() print x  E:/study/python/workspace>xianchengtongbu2.py 1000000 0 0 

Inter-thread communication:

The Event object is used for inter-thread communication. It provides setting signals, clearing letter macros, and waiting for inter-thread communication.

1. Set the signal. After the Event object uses the set () method, the isSet () method returns true.
2. Clear the signal. After the clear () method of the Event object is used, the isSet () method returns false.
3. Wait. When the internal signal of the Event object is false, the wait () method will not return until it is true. You can also pass parameters to wait to set the maximum wait time.

#-*-Coding: UTF-8-*-import threading class mythread (threading. thread): def _ init _ (self, threadname): threading. thread. _ init _ (self, name = threadname) def run (self): global event if event. isSet (): event. clear () event. wait () # print self is returned only when the event is marked. getName () else: print self. getName () event. set () event = threading. event () event. set () t1 = [] for I in range (10): t = mythread (str (I) t1.append (t) for I in t1: I. start ()

If you have any questions, please leave a message or go to the community on this site for discussion. Thank you for reading this article. Thank you for your support!

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.