A concise example of trying multithreaded programming in Python

Source: Internet
Author: User
Review
Multithreading is an important aspect of program design, especially in Server Deamon program. Regardless of the system, the overhead of thread scheduling is much faster than the traditional process.
Python makes it easy to support multithreading. You can quickly create threads, mutexes, semaphores, and so on, enabling threads to read and write synchronous mutexes. In the ointment, Python runs on a python virtual machine, creating multithreading that could be virtual threads that need to be polled by a Python virtual machine for scheduling, which greatly reduces the availability of Python multi-threading. Hopefully the higher version of Python will solve this problem and maximize the efficiency of multiple CPUs.
Some friends on the internet say there are two ways to get real multi-CPU benefits:
1. You can create multiple processes instead of threads, with as many processes as CPUs.
2. Using Jython or IronPython, you can get real multithreading.
Talk less, see how Python Builds threads
Python thread creation
Thread class using the threading module
The class interface is as follows
Copy CodeThe code is as follows:

Class Thread (Group=none, Target=none, Name=none, args= (), kwargs={})


The parameters that need attention are target and args. Target is the objective function that requires a sub-thread to run, and args is the parameter of the function passed in the form of a tuple.
The following code creates a child thread that points to a function worker
Copy CodeThe code is as follows:

def worker (A_tid,a_account):
...
th = Threading. Thread (target=worker,args= (I,ACC));

Start this thread
Copy the Code code as follows:

Th.start ()


wait for thread to return
Copy CodeThe code is as follows:

Threading. Thread.Join (TH)


or Th.join ()
If you can partition the data you want to work with, and you don't need to communicate between threads, you can write your multithreaded program in a way that: Create = "Run =" recycle. However, if you need to access common objects between threads, you need to introduce a mutex or semaphore to mutually exclusive access to the resource.
Here's how to create a mutex
Create a lock
Copy CodeThe code is as follows:

G_mutex = Threading. Lock ()
....


using Locks
Copy CodeThe code is as follows:

For ...:
#锁定, from the next line of code to exclusive access before release
G_mutex.acquire ()
A_account.deposite (1)
#释放
G_mutex.release ()


Finally, it simulates a multi-thread of bus subway IC card paying fare.
There are 10 card readers, each card reader fee deduction User A piece of money into the general ledger, each card reader is brushed 10 million times a day. The original account is 100 dollars. So the final ledger should be 10000100. Do not use a mutex to lock (comment out the lock code), to see the consequences.

Import Time,datetimeimport 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, DAT Etime.datetime.now ()) class Account:def __init__ (Self, a_base): Self.m_amount=a_base def deposite (self,a_amount): s Elf.m_amount+=a_amount def withdraw (self,a_amount): self.m_amount-=a_amount If __name__ = "__main__": Global G_mutex Co UNT = 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 (+) for I in range: th = Threading.  Thread (target=worker,args= (I,ACC)); Thread_pool.append (TH) # start threads one by one for me in range: Thread_pool[i].start () #collect All threads For I in range: 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 that the critical section access control is not performed without a mutex, and the result is as follows:

As you can see from the results, the program is running multithreaded. However, because there is no mutually exclusive access to the object account, the result is wrong, only 3434612, a lot less than the original estimate.

After opening the lock:

This time we can see that the results are correct. Running time is a lot more than not being mutually exclusive, but this is also the cost of synchronization.
At the same time, write multi-threading, multi-Process class program, can not be used with the idle to run. There will be errors.

  • 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.