Simple Example of Python Multithreading

Source: Internet
Author: User

Summary

Multithreading is Program An important aspect of the design, especially in the deamon program of the server. Regardless of the system, the thread scheduling overhead is much faster than the traditional process.
Python supports multiple threads. Allows you to quickly create threads, mutex locks, semaphores, and other elements, and supports synchronization and mutex between read and write threads. The disadvantage is that python runs in Python
On a virtual machine, the multi-thread created may be a virtual thread and needs to be polling and scheduled by the python virtual machine, which greatly reduces the availability of the python multi-thread. Hope that python of later versions can
Solve this problem and maximize the efficiency of multiple CPUs. Some friends on the Internet say that there are two ways to achieve the benefits of real multi-CPU: 1. You can create multiple processes rather than threads, and the number of processes is the same as that of CPU.
2. Using Jython or ironpython, you can get real multithreading. Let's talk about how to create a thread in Python. Create a python thread

The thread class interfaces of the threading module are as follows: Class
Thread (group = none, target = none, name = none, argS = (), kwargs = {}) parameters to be concerned are target and args. target is the target function that requires sub-threads to run, and ARGs is the parameter of the function, which is passed in the form of tuple. Below Code Create a subthread pointing to the worker Function
Def worker (a_tid, a_account ):

...


Th = threading. Thread (target = worker, argS = (I, ACC); start this thread
Th. Start () waits for the thread to return
Threading. thread. Join (th)

Or th. join () If you can well divide the data to be processed without communication between threads, you can use: create = run = recycle to write your multi-threaded program. However, if the threads need to access a common object, the mutex lock or semaphore must be introduced to access resources mutex. The following describes how to create a mutex lock. Create lock


G_mutex = threading. Lock ()


....
Use lock



For
...:

# Lock, mutual access exclusive from the next code to before release

G_mutex.acquire ()

A_account.deposite (1)

# Release

G_mutex.release () Finally, a multi-threaded program simulating the fare payment of an IC card for a Public Transit Subway has 10 card readers. Each card reader enters the general ledger after each deduction of a user's money, each card reader is refreshed 10000000 times a day. 100 original accounts. So the final general account should be 10000100. First, do not use mutex lock for locking (comment out the lock code) to see the consequences. Import time, datetime
Import threading

Def worker (a_tid, a_account ):
Global g_mutex
Print "str", a_tid, datetime. datetime. Now ()
For I in range (1000000 ):
# G_mutex.acquire ()
A_account.deposite (1)
# G_mutex.release ()

Print "end", a_tid, datetime. datetime. Now ()

Class account:
Def _ init _ (self, a_base ):
Self. m_amount = a_base
Def deposite (self, a_amount ):
Self. m_amount + = a_amount
Def withdraw (self, a_amount ):
Self. m_amount-= a_amount

If _ name _ = "_ main __":
Global g_mutex
Count = 0
Dstart = datetime. datetime. Now ()
Print "main thread start at:", dstart

# Init thread_pool
Thread_pool = []
# Init mutex
G_mutex = threading. Lock ()
# Init thread items
ACC = Account (100)
For I in range (10 ):
Th = threading. Thread (target = worker, argS = (I, ACC ));
Thread_pool.append (th)

# Start threads one by one
For I in range (10 ):
Thread_pool [I]. Start ()

# Collect all threads
For I in range (10 ):
Threading. thread. Join (thread_pool [I])
Dend = datetime. datetime. Now ()
Print "Count =", ACC. m_amount
Print "main thread end at:", dend, "time span", dend-dstart; Note: Do not use mutex lock to control access to critical segments. The running result is as follows: main thread start at: 00:17:55. 296000
STR 0 2009-01-13 00:17:55. 312000
STR 1 00:17:55. 453000
STR 2 00:17:55. 484000
STR 3 2009-01-13 00:17:55. 531000
STR 4 2009-01-13 00:17:55. 562000
STR 5 00:17:55. 609000
STR 6 2009-01-13 00:17:55. 640000
STR 7 00:17:55. 687000
STR 8 00:17:55. 718000
STR 9 00:17:55. 781000
End 0 00:18:06. 250000
End 1 00:18:07. 500000
End 4 00:18:07. 531000
End 2 00:18:07. 562000
End 3 00:18:07. 593000
End 9 00:18:07. 609000
End 7 00:18:07. 640000
End 8 00:18:07. 671000
End 5 00:18:07. 687000
End 6 00:18:07. 718000
Count = 3434612
Main thread end at: 00:18:07. 718000 time span 0:00:12. 422000 from the results, we can see that the program runs in multiple threads. However, because no mutex access is made to the object account, the result is incorrect, only 3434612, much less than expected. Open the comment of the Shadow code above. The running result is as follows: main thread start at: 00:26:12. 156000
STR 0 2009-01-13 00:26:12. 156000
STR 1 00:26:12. 390000
STR 2 00:26:12. 437000
STR 3 2009-01-13 00:26:12. 468000
STR 4 2009-01-13 00:26:12. 515000
STR 5 00:26:12. 562000
STR 6 2009-01-13 00:26:12. 593000
STR 7 00:26:12. 640000
STR 8 00:26:12. 671000
STR 9 00:26:12. 718000
End 0 00:27:01. 781000
End 1 00:27:05. 890000
End 5 00:27:06. 046000
End 7 00:27:06. 078000
End 4 00:27:06. 109000
End 2 00:27:06. 140000
End 6 00:27:06. 156000
End 8 00:27:06. 187000
End 3 00:27:06. 203000
End 9 00:27:06. 234000
Count = 10000100
Main thread end at: 00:27:06. 234000 time span 0:00:54. 078000 this time we can see that the result is correct. Running time is much longer than not mutex. It takes 54 seconds to run (my machine is rotten and there is no money to update it), but this is also the cost of synchronization, no way.

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.