Python multithreaded Programming (2): Synchronizing threads with mutex

Source: Internet
Author: User

In the example in the previous section, each thread is independent of each other and has no relationship to each other. Now suppose such an example: there is a global count num, each thread gets the global count, does some processing based on NUM, and then adds Num 1. It's easy to write code like this:

# Encoding:utf-8
Import threading
Import time

Class MyThread (threading. Thread):
def run (self):
Global num
Time.sleep (1)
num = num+1
msg = self.name+ ' Set num to ' +str (num)
Print msg
num = 0
def test ():
For I in range (5):
t = MyThread ()
T.start ()
if __name__ = = ' __main__ ':
Test ()

However, the result is not correct:

Thread-5 Set num to 2
Thread-3 Set num to 3
Thread-2 Set num to 5
Thread-1 Set num to 5
Thread-4 Set num to 4

The problem arises because there is no control over the access of multiple threads to the same resource, causing damage to the data and making the results of the thread run unpredictable. This behavior is called "Thread insecurity."

Mutual exclusion Lock Synchronization

The above example leads to the most common problem with multithreaded programming: Data sharing. Synchronization control is required when multiple threads modify a shared data.

Thread synchronization ensures that multiple threads secure access to competing resources, and the simplest synchronization mechanism is to introduce mutexes. A mutex introduces a state to a resource: locked/non-locked. When a thread changes the shared data, it locks it, the state of the resource is locked, the other thread cannot be changed, and until the thread frees the resource, the state of the resource becomes "non-locked", and the other thread can lock the resource again. The mutex ensures that only one thread is written at a time, thus guaranteeing the correctness of the data in multi-threaded situations.

The lock class is defined in the threading module, allowing for easy handling of locks:

#创建锁
Mutex = Threading. Lock ()
#锁定
Mutex.acquire ([timeout])
#释放
Mutex.release ()

Where the lock method acquire can have a time-out optional parameter of timeout. If timeout is set, the return value after timeout can be used to determine if a lock has been obtained, allowing for some additional processing.

The code for implementing the above example using a mutex is as follows:

ImportThreadingImport TimeclassMyThread (Threading. Thread):defRun (self):GlobalNum Time.sleep (1)                ifMutex.acquire (1): Num+ = 1msg= self.name+'Set num to'+str (num)Printmsg mutex.release () num=0mutex=Threading. Lock ()defTest (): forIinchRange (5): T=MyThread () T.start ( )if __name__=='__main__': Test ()

Operation Result:

Thread-3 Set num to 1
Thread-4 Set num to 2
Thread-5 Set num to 3
Thread-2 Set num to 4
Thread-1 Set num to 5

As you can see, after joining the mutex, the running result matches the expected.

Synchronous blocking

When a thread calls the lock's acquire () method to obtain the lock, the lock enters the "locked" state. Only one thread can get a lock at a time. If another thread attempts to acquire the lock at this point, the thread becomes a "blocked" state called "synchronous blocking" (see Basic concepts of multithreading).

The lock enters the "unlocked" state until the lock's release () method is called by the thread that owns the lock. The thread scheduler chooses one of the threads in the synchronous blocking state to obtain the lock and causes the thread to enter the running (running) state.

The basic content of mutexes is these, and the next section discusses the Reentrant lock (Rlock) and deadlock issues.

Python multithreaded Programming (2): Synchronizing threads with mutex

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.