Python Multithreading--thread synchronization

Source: Internet
Author: User

If multiple threads are working together on a data modification, unpredictable results may occur, and multiple threads need to be synchronized in order to ensure the correctness of the data.

Using the thread object's lock and Rlock allows for simple thread synchronization, both of which have the acquire method and the release method, which can be placed between the acquire and release methods for data that requires only one thread to be allowed to operate at a time. 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.

#Coding=utf-8#!/usr/bin/pythonImportThreadingImport TimeclassMyThread (Threading. Thread):def __init__(self, ThreadID, name, counter): Threading. Thread.__init__(self) self.threadid=ThreadID Self.name=name Self.counter=counterdefRun (self):Print "starting"+Self.name#Gets the lock and returns true after the lock is successfully obtained       #The optional Timeout parameter is blocked until the lock is obtained       #Otherwise, the time-out will return falseThreadlock.acquire () print_time (Self.name, Self.counter,3)        #Release Lockthreadlock.release ()defprint_time (threadname, Delay, counter): whileCounter:time.sleep (Delay)Print "%s:%s"%(ThreadName, Time.ctime (Time.time ())) counter-= 1Threadlock=Threading. Lock () Threads= []#Create a new threadThread1 = MyThread (1,"Thread-1", 1) Thread2= MyThread (2,"Thread-2", 2)#Open new ThreadThread1.start () Thread2.start ( )#add thread to Thread listthreads.append (thread1) threads.append (thread2)#wait for all threads to complete forTinchThreads:t.join ()Print "Exiting Main Thread"

Python Multithreading--thread synchronization

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.