What is Python thread synchronization? Read the Python threading module in one article

Source: Internet
Author: User
If multiple threads are working together on a data modification, unpredictable results may occur, and in order to ensure the correctness of the data, it is necessary to synchronization of multiple threads

Using the thread object's lock and Rlock allows for simple thread synchronization , both of which have the acquire method and the release method, for those data that require only one thread at a time, You can put its actions between the acquire and the release methods. As follows:

The advantage of multithreading is that you can run multiple tasks at the same time (at least it feels like this). However, when a thread needs to share data, there may be an issue with data that is out of sync.

Consider a situation in which all elements in a list are 0, the thread "set" changes all elements to 1 from the back, and the thread "print" is responsible for reading the list and printing from the front.

Then, when the thread "set" starts to change, the thread "print" will print the list, and the output will be half 01 and a half 1, which is a different step in the data. In order to avoid this situation, the concept of lock is introduced.

The lock has two states-locked and unlocked. Each time a thread such as "set" is to access the shared data, the lock must first be acquired, and if another thread such as "print" is locked, then the thread "set" is paused, that is, the synchronization is blocked, and the thread "set" continues after the thread "print" has been accessed, releasing the lock.

After this processing, the print list will either output 0, or all output 1, no more than half 1 and a half 1 embarrassing scenes.

#!/usr/bin/python#-*-coding:utf-8-*-import threadingimport timeclass myThread (Threading. Thread):d EF __init__ (self, ThreadID, name, counter): Threading. Thread.__init__ (self) self.threadid = Threadidself.name = Nameself.counter = Counterdef run (self):p rint ' starting ' + self . name# gets the lock and returns true# when the optional timeout parameter is not filled will block until the lock is obtained # otherwise the timeout will return Falsethreadlock.acquire () print_time (Self.name, Self.counter, 3) # Release lock Threadlock.release () def print_time (threadname, Delay, counter): while Counter:time.sleep (delay) Print "%s:%s"% (ThreadName, Time.ctime (Time.time ())) counter-= 1threadLock = Threading. Lock () threads = []# Create new Thread thread1 = MyThread (1, "Thread-1", 1) thread2 = MyThread (2, "Thread-2", 2) # Open new Thread Thread1.start () thr Ead2.start () # Add thread to Thread list threads.append (thread1) Threads.append (thread2) # Wait for all threads to finish for T in Threads:t.join () print " Exiting Main Thread "
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.