A concise example of trying multithreaded programming in Python _python

Source: Internet
Author: User
Tags mutex thread class in python

Review
multithreading is an important aspect of programming, especially in server Deamon programs. In any system, the cost of thread scheduling is much faster than the traditional process.
Python can easily support multithreading. You can quickly create elements such as threads, mutexes, semaphores, and so on that support thread read-write synchronization mutexes. The drawback is that Python is running on a Python virtual machine, creating multithreading that might be virtual threads that need to be polled by Python virtual machines, which greatly reduces the availability of Python threads. Hopefully, a high version of Python can solve this problem and maximize the CPU's maximum efficiency.
Some friends on the internet say there are two ways to get the benefits of really multiple CPUs:
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.
Less gossip, let's see how Python Builds threads
Python thread creation
Thread class using the threading module
The class interface is as follows

Copy Code code as follows:
Class Thread (Group=none, Target=none, Name=none, args= (), kwargs={})

The parameters to be concerned are target and args. Target is the objective function that requires the child thread to run, and the args is the parameter of the function, passed in tuple form.
The following code creates a child thread that points to the function worker
Copy Code code as follows:
def worker (A_tid,a_account):
...
th = Threading. Thread (target=worker,args= (I,ACC));

Start this thread

Copy Code code as follows:
Th.start ()

wait for thread to return
Copy Code code as follows:
Threading. Thread.Join (TH)

or Th.join ()
If you can do a good job of dividing the data to be processed, and there is no communication between threads, then you can write your multithreaded program in the form of "Run =" "Recycle". 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.
Let's talk about how to create a mutual exclusion lock
Creating locks
Copy Code code as follows:
G_mutex = Threading. Lock ()
....

using Locks
Copy Code code as follows:
For ...:
#锁定, mutex access from next code to before release
G_mutex.acquire ()
A_account.deposite (1)
#释放
G_mutex.release ()

Finally, the simulation of a bus subway IC card payment of the multi-thread routines
There are 10 card readers, each card reader fee per 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 pieces. So the final general ledger should be 10000100. Lock the lock without using a mutex (comment out the locking code) and see what happens.

Import time,datetime Import Threading def Worker (A_tid,a_account): Global G_mutex print ("Str", A_tid, Datetime.date Time.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 (sel F,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_poo L Thread_pool = [] #init Mutex G_mutex = threading. Lock () # init thread Items ACC = account (m) in range (a): th = Threading.
  Thread (target=worker,args= (I,ACC)); Thread_pool.append (TH) # start threads one by one for I-in range (a): Thread_pool[i].start () #collect all th Reads for I in range: Threading. Thread.Join (thread_pool[i]) DEnd = Datetime.dateTime.now () print ("count=", Acc.m_amount) print ("Main Thread End in:", DEnd, "time span", Dend-dstart)

 

Note that a critical segment access control is not necessary without a mutex, and the results are as follows:

As you can see from the results, the program is actually multithreaded. But because there is no mutex access to the object account, the result is wrong, only 3434612, a lot less than originally expected.

After opening the lock:

This time we can see that the results are correct. It's a lot more than a mutex, but it's also the price of synchronization.
At the same time, it is found that the program of writing multiple threads and multiple process classes cannot be run with idle. There will be mistakes.

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.