Python Threading Module Multithreaded source Example (ii) __python

Source: Internet
Author: User

I. Overview of ideas

Python thread creation
The interface of the Thread class using the threading module is as follows
Class Thread (Group=none, Target=none, Name=none, args= (), kwargs={})
&NBSP
The parameters you need to focus on are target and args. targets are the objective functions that require child threads to run, args are parameters of the function, and are passed in tuple form.
The following code creates a child thread that points to the function worker
Def worker (Tid,account):  
    ...  
 
th = threading . Thread (target=worker,args= (I,ACC));
 
To start this thread
Th.start ()
 
Wait for threads to return or reclaim thread resources
Threading. Thread.Join (TH)  
or Th.join ()
 
If you can make a good division of the data to be processed and there is no communication between threads, then you can use: Create = "Run =" Recycle the way you write your multithreaded program. However, if you need to access a common object between threads, you need to introduce a mutex or a semaphore to mutually exclusive access to the resource.
 
How to create a mutex
Create a lock  
G_mutex = Threading. Lock ()  
...  
uses the lock  
for ...:  
        #锁定, mutual exclusion access from the next code to the release  < br>         G_mutex.acquire ()  
        A_account.deposite (1)  
& nbsp       #释放  
        g_mutex.release ()

Two. Business needs

Simulation of a bus subway IC card payment of the multi-thread routines
Suppose there are 10 card readers, each card reader fee per deduction User A piece of money into the general ledger, each card reader is a total of 1 million times a day. The original account is 100 pieces. So the final general ledger should be 10000100.

Three. Source Code realization

#!/usr/bin/env python #encoding: Utf-8 import Time, datetime, threading #each worker thread Exec-1000000 times def Worke
            R (Tid, account): Global G_mutex to I in range (1000000): G_mutex.acquire () If i%500000 = 0: print ' worker thread ', Tid, ' count ', I account.deposite (1) g_mutex.release () #account operation CL Ass class Account:def __init__ (self, base): Self.m_amount = base def deposite (self, amount): Sel

    F.m_amount + = amount; def withdraw (self, amount): self.m_amount-= Amount #main entry point ... if __name__ = = ' __main__ ': Global g
    _mutex count = 0; Tm_start = Datetime.datetime.now () print ' Main thread start at: ', Tm_start #initialize Thread pool Thread_poo L = [] #initialize Mutex G_mutex = threading. Lock () #init thread Items acc = account to I in range (Ten): T = Threading.
        Thread (Target=worker, args= (i, ACC)); Thread_pool.appenD (t) #start worker threads One by one for I in range: Thread_pool[i].start () #reclaim all worker Threads resource for I in range: Threading. Thread.Join (Thread_pool[i]) #statistics tm_stop = Datetime.datetime.now () print ' count= ', Acc.m_amount PR
 int ' Main Thread end in: ', tm_stop print ' time consumption ', Tm_stop-tm_start

Four. Operation Effect screenshot

Note that in a multithreaded environment the print output should be placed under a mutex to not cause confusion about the printing information of each thread.


Reference documents

[1].http://blog.csdn.net/liangpz521/article/details/8906861

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.