Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use threading Library to realize Thread Lock and release Lock in Python

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces the relevant knowledge of "how Python uses threading library to achieve thread lock and release lock". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Control resource access

As mentioned earlier, when the threading library is multithreaded, the access to the same resource can easily lead to destruction and loss of data. To ensure secure access to a resource object, we need to create a lock.

Examples are as follows:

Import threadingimport timeclass AddThread (): def _ _ init__ (self Start=0): self.lock = threading.Lock () self.value = start def increment (self): print ("Wait Lock") self.lock.acquire () try: print ("Acquire Lock") self.value + = 1 print (self.value) finally: self.lock.release () def worker (a): Time.sleep (1) a.increment () addThread = AddThread () for i in range (3): t = threading.Thread (target=worker) Args= (addThread,) t.start ()

Acquire () blocks the execution of the intermediate segment by locking other threads, and release () releases the lock, which, as you can see, is basically executed after the lock is acquired. Avoid multiple threads changing their resource objects at the same time without causing confusion.

Determine if another thread requests a lock

To determine whether another thread requests a lock without affecting the current thread, you can set the parameter blocking=False of acquire ().

Examples are as follows:

Import threadingimport timedef worker2 (lock): print ("worker2 Wait Lock") while True: lock.acquire () try: print ("Holding") time.sleep (0.5) finally: print ("not Holding") lock.release () time.sleep (0.5) def worker1 (lock): print ("worker1 Wait Lock" ") num_acquire = 0 value = 0 while num_acquire < 3: time.sleep (0.5) have_it = lock.acquire (blocking=False) try: value + = 1 print (value) print (" Acquire Lock ") if have_it: num_acquire + = 1 finally: print ("release Lock") if have_it: lock.release () lock = threading.Lock () word2Thread = threading.Thread (target=worker2 Name='work2', args= (lock,) word2Thread.start () word1Thread = threading.Thread (target=worker1, name='work1', args= (lock,)) word1Thread.start ()

Here, we need to iterate many times before work1 can acquire the lock three times. But I tried it eight times.

With lock

Earlier, we achieved lock acquisition and release through lock.acquire () and lock.release (), but in fact, our Python also provides us with a simpler syntax to acquire and release locks through with lock.

Examples are as follows:

Import threadingimport timeclass AddThread (): def _ _ init__ (self Start=0): self.lock = threading.Lock () self.value = start def increment (self): print ("Wait Lock") with self.lock: print ("lock acquire") self.value + = 1 print (self.value) print ("lock release") def worker (a): time.sleep (1) a.increment () addThread = AddThread () for i in range (3): t = threading.Thread (target=worker Args= (addThread,) t.start ()

It is important to note that a normal Lock object cannot be requested multiple times, even by the same thread. An accident occurs if multiple functions in the same call chain access a lock. Use RLock in this case if you expect different code on the same thread to need to regain the lock.

Synchronization thread Condition

In practice, we can also use the Condition object to synchronize threads. Because Condition uses a Lock, it can be bound to a shared resource, allowing multiple threads to wait for updates to the resource.

Examples are as follows:

Import threadingimport timedef consumer (cond): print ("waitCon") with cond: cond.wait () print ('get updated resources') def producer (cond): print ("worker") with cond: print ('updated resources') cond.notifyAll () cond = threading.Condition () T1 = threading.Thread (name='t1', target=consumer, args= (cond,)) T2 = threading.Thread (name='t2', target=consumer, args= (cond) )) T3 = threading.Thread (name='t3', target=producer, args= (cond,)) t1.start () time.sleep (0.2) t2.start () time.sleep (0.2) t3.start ()

Here, we call notifyAll (), consumer and other threads after producer threading is finished to update it, which can be compared to the observer mode. Here, when a thread runs out of resources, it automatically notifies all threads that depend on it.

Barrier (barrier)

The barrier is another thread synchronization mechanism. Barrier establishes a control point where all participating threads block until all of these participants reach this point. With this approach, threads can be started separately and then paused until all threads are ready to continue.

Examples are as follows:

Import threadingimport timedef worker (barrier): print (threading.current_thread (). GetName (), "worker") worker_id = barrier.wait () print (threading.current_thread (). GetName (), worker_id) threads = [] barrier = threading.Barrier (3) for i in range (3): threads.append (threading.Thread (name= "t" + str (I), target=worker, args= (barrier) ) for tin threads: print (t.name, 'starting') t.start () time.sleep (0.1) for tin threads: t.join ()

From the output from the console, it is found that barrier.wait () blocks threads until all threads have been created, releasing execution beyond this control point at the same time. The return value of wait () indicates the number of participating threads released, which can be used to restrict some threads from doing actions such as cleaning up resources.

Of course, the barrier Barrier also has an abort () method, which causes all waiting threads to receive a BroKenBarrierError. This exception is generated if the thread is blocked on wait () and stops processing, and the cleanup can be done through except.

Concurrent access to limited resources

In addition to the fact that multiple threads may access the same resource, sometimes we limit the number of multithreaded access to the same resource for the sake of performance. For example, thread pools support simultaneous connections, but the data may be fixed, or the number of concurrent downloads provided by a network APP supports a fixed number. These connections can then be managed using Semaphore.

Examples are as follows:

Import threadingimport timeclass WorkerThread (threading.Thread): def _ init__ (self): super (WorkerThread, self). _ _ init__ () self.lock = threading.Lock () self.value = 0 def increment (self): with self.lock: self.value + = 1 print (self.value) def worker (s Pool): with s: print (threading.current_thread (). GetName () pool.increment () time.sleep (1) pool.increment () pool = WorkerThread () s = threading.Semaphore (2) for i in range (5): t = threading.Thread (name= "t" + str (I), target=worker, args= (s, pool,)) t.start ()

Hide resources

In a real project, some resources need to be locked for use by multiple threads, while others need to be protected so that they are hidden from threads that are not the owners of those resources.

The local () function creates an object that hides values so that they cannot be seen in different threads. Examples are as follows:

Import threadingimport randomdef show_data (data): try: result = data.value except AttributeError: print (threading.current_thread (). GetName (), "No value") else: print (threading.current_thread (). GetName (), "value=", result) def worker (data): show_data (data) data.value = random.randint (1 Show_data (data) local_data = threading.local () show_data (local_data) local_data.value = 1000show_data (local_data) for i in range (2): t = threading.Thread (name= "t" + str (I), target=worker, args= (local_data,)) t.start () "how to use the threading library to implement thread locks and release locks" ends here Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report