python-Multi-Threading 2-Thread synchronization

Source: Internet
Author: User

Thread synchronization:

A scene:

All elements in a list are 0, and thread a forwards all the elements to 1, while thread B is responsible for reading the list and printing from the front.

Then, when thread a starts to change, thread B prints the list, and the output becomes half 01 and a half 1, which is a different step in the data

Thread synchronization is to prevent this, but also introduces the concept of lock. Lock and Rlock can implement thread synchronization. Both of these objects have

The Acquire method and the release method can be placed between the acquire and release methods for data that requires only one thread to be allowed to operate at a time.

You can understand that the things between these two methods will be locked.

Each time a thread such as a wants to access the shared data, it must first obtain a lock, if there is already another thread such as B to get locked, then let thread a pause,

That is, synchronous blocking; Wait until thread B is finished, release the lock, and then let thread a continue

After this processing, the print list is either all output 0, or all output 1, no more than half 1 and a half 1

Common methods:

Threading. Lock () The same thread cannot be acquire multiple times, otherwise the deadlock

Threading. Rlock () The same thread allows continuous acquire, but acquire and release must appear in pairs

ImportThreadingImportTime#used for pauses.classMyThread (Threading. Thread):#with multi-threading, you must inherit the parent class threading. Thread    def __init__(Self,threadid,name,counter): Threading. Thread.__init__(self)#fixed format, equivalent to initialization of threadsSelf.threadid =ThreadID Self.name=name Self.counter=counterPrint('initialization Complete')            defRun (self):#you cannot determine the order in which run () executes between different threads, which is determined by CPU processing .        Print("Start Thread"+self.name)#Gets the lock, returns True when the lock is successfully obtained, and blocks until the optional timeout parameter is not filled until the lock is acquiredThreadlock.acquire () print_time (Self.name,self.counter,3)        #Release the lock and start the next threadthreadlock.release ()defPrint_time (threadname,counter,delay): whileCounter:time.sleep (Delay)#Pause 5s        Print("%s:%s"% (Threadname,time.ctime (Time.time ())))#print thread name and timeCounter = counter-1Threadlock= Threading. Lock ()#The Threadlock method returns a value that is received with the variableThreads = []#ignore this sentence for the time being#Create a thread, generate two objectsThread1 = MyThread (1,"Thread-1", 1) Thread2= MyThread (2,"Thread-2", 2)#Open ThreadThread1.start ()#starting the thread, each thread object must call the function at least once, and he will automatically call the run () methodThread2.start ()#append two threads to an empty listthreads.append (thread1) threads.append (thread2)#join ([TIME]) waits until the thread aborts. This blocks the calling thread until the thread's join () method is called aborted, exits gracefully, or throws#Unhandled exception, or optional timeout counter#detects if the thread is all running, waits for completion, and then executes the content after the join () forTinchThreads:t.join ()Print("I waited until the flowers also thanked, the sea son also cried, well, deserved ...")

Results:

Initialization complete
Initialization complete
Start Thread Thread-1
Start Thread Thread-2
Thread-1:sat June 17 01:22:44 2017
Thread-2:sat June 17 01:22:47 2017
Thread-2:sat June 17 01:22:50 2017
I waited until the flowers also thanked, the sea son also cried, well, deserved ...

python-Multi-Threading 2-Thread synchronization

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.