Home > Article > Backend Development > What is Python thread synchronization? Understand the Python thread module in one article
If multiple threads jointly modify a certain data, unpredictable results may occur. In order to ensure the accuracy of the data, multiple threads need to be synchronized.
Using the Lock and Rlock of the Thread object can achieve simple Thread synchronization. Both objects have acquire methods and release methods, for those data that require only one thread to operate at a time. , its operation can be placed between the acquire and release methods. As follows:
The advantage of multi-threading is that it can run multiple tasks at the same time (at least it feels like this). But when threads need to share data, there may be data out-of-synchronization problems.
Consider this situation: all elements in a list are 0, thread "set" changes all elements to 1 from back to front, and thread "print" is responsible for reading the list from front to back and printing .
Then, maybe when the thread "set" starts to change, the thread "print" will print the list, and the output will be half 0 and half 1. This is the desynchronization of the data. To avoid this situation, the concept of locks was introduced.
Locks have two states - locked and unlocked. Whenever a thread such as "set" wants to access shared data, it must first obtain the lock; if another thread such as "print" has obtained the lock, then let the thread "set" pause, which is synchronous blocking; wait until the thread " Print "After the access is completed and the lock is released, let the thread "set" continue.
After such processing, when printing the list, either all 0s or all 1s will be output, and there will no longer be an embarrassing scene of half 0s and half 1s.
#!/usr/bin/python # -*- coding: UTF-8 -*- import threading import time class myThread (threading.Thread): def __init__(self, threadID, name, counter): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.counter = counter def run(self): print "Starting " + self.name # 获得锁,成功获得锁定后返回True# 可选的timeout参数不填时将一直阻塞直到获得锁定 # 否则超时后将返回False threadLock.acquire() print_time(self.name, self.counter, 3) # 释放锁 threadLock.release() def print_time(threadName, delay, counter): while counter: time.sleep(delay) print "%s: %s" % (threadName, time.ctime(time.time())) counter -= 1 threadLock = threading.Lock() threads = [] # 创建新线程 thread1 = myThread(1, "Thread-1", 1) thread2 = myThread(2, "Thread-2", 2) # 开启新线程 thread1.start() thread2.start() # 添加线程到线程列表 threads.append(thread1) threads.append(thread2) # 等待所有线程完成 for t in threads: t.join() print "Exiting Main Thread"
The above is the detailed content of What is Python thread synchronization? Understand the Python thread module in one article. For more information, please follow other related articles on the PHP Chinese website!