For example, in Python programming, the thread lock

Source: Internet
Author: User
Python's threading module provides a variety of lock-related methods, Python multi-threaded can not be executed at the same time, so the use of locks is very critical, we will give an example of Python programming in the use of the thread Lock:

Lock

Python's built-in data structures, such as lists and dictionaries, are thread-safe, but simple types such as integers and floating-point numbers are not thread-safe, and locks are required to operate on these simple data types.

#!/usr/bin/env python3# Coding=utf-8import threadingshared_resource_with_lock = 0shared_resource_with_no_lock = 0COUNT = 100000shared_resource_lock = Threading. Lock () # # # #LOCK management# #def increment_with_lock (): Global shared_resource_with_lock for I in Range (COUNT): Shared_  Resource_lock.acquire () Shared_resource_with_lock + = 1 shared_resource_lock.release () def decrement_with_lock (): Global Shared_resource_with_lock for I in Range (COUNT): Shared_resource_lock.acquire () Shared_resource_with_lock- = 1 Shared_resource_lock.release () # # # #NO Lock MANAGEMENT # def increment_without_lock (): Global Shared_resource_ With_no_lock for I in Range (COUNT): Shared_resource_with_no_lock + = 1 def decrement_without_lock (): Global shared_re Source_with_no_lock for I in Range (COUNT): Shared_resource_with_no_lock-= 1 # # # #the Main programif __name__ = = "__ma in__ ": T1 = Threading. Thread (target = increment_with_lock) t2 = Threading. Thread (target = decrement_with_lock) t3 = Threading. Thread (target = increment_without_lock) T4 = Threading.  Thread (target = decrement_without_lock) T1.start () T2.start () T3.start () T4.start () T1.join () T2.join () T3.join () T4.join () print ("The value of shared variable with lock management is%s" \%shared_resource_with_lock) Print ("The Val UE of shared variable with race condition is%s "\%shared_resource_with_no_lock)

Execution Result:

$./threading_lock.py

The value of shared variable with lock management is 0the value of GKFX variable with race condition is 0

Another example:

Import Randomimport threadingimport timelogging.basicconfig (level=logging. DEBUG, format= ' (% (threadname) -10s)% (message) s ',) class Counter (object): Def __init__ (self, S tart=0): Self.lock = Threading.  Lock () Self.value = Start def increment (self): Logging.debug (Time.ctime (Time.time ())) Logging.debug (' Waiting for Lock ') self.lock.acquire () Try:pause = Random.randint (1,3) logging.debug (Time.ctime (Time.time ())) L      Ogging.debug (' acquired lock ') Self.value = self.value + 1 logging.debug (' lock {0} seconds '. Format (pause)) Time.sleep (pause) finally:self.lock.release () def worker (c): For I in range (2): pause = random.randint (1, 3) Logging.debug (Time.ctime (Time.time ())) Logging.debug (' Sleeping%0.02f ', pause) time.sleep (pause) c.incremen T () logging.debug (' done ') counter = counter () for I in Range (2): T = Threading. Thread (Target=worker, args= (counter,)) T.start () Logging.debug (' Waiting for WorkeR threads ') Main_thread = Threading.currentthread () for T in Threading.enumerate (): If T isn't main_thread:t.join () log Ging.debug (' Counter:%d ', counter.value)

Execution Result:

$ python threading_lock.py

(Thread-1) Tue Sep 15:49:18 (Thread-1) sleeping 3.00 (Thread-2) Tue Sep 15:49:18 (mainthread) waiting for worker Threa  DS (Thread-2) sleeping 2.00 (Thread-2) Tue Sep 15:49:20 (Thread-2) Waiting for Lock (Thread-2) Tue Sep 15 15:49:20 (THREAD-2) acquired lock (Thread-2) lock 2 seconds (Thread-1) Tue Sep 15:49:21 (Thread-1) Waiting for Lock (T hread-2) Tue Sep 15:49:22 (Thread-1) Tue Sep 15:49:22 (Thread-2) sleeping 2.00 (Thread-1) acquired lock (T Hread-1) lock 1 seconds (Thread-1) Tue Sep 15:49:23 (Thread-1) sleeping 2.00 (Thread-2) Tue Sep 15 15:49:24 2015 ( Thread-2) Waiting for Lock (Thread-2) Tue Sep 15:49:24 (Thread-2) acquired lock (Thread-2) lock 1 seconds (thread- 1) Tue Sep 15:49:25 (Thread-1) Waiting for Lock (Thread-1) Tue Sep 15:49:25 (Thread-1) acquired lock (thre Ad-1) lock 2 seconds (Thread-2) done (Thread-1) done (mainthread) counter:4

False value passed in acquire () to check if a lock was obtained. Like what:

Import Loggingimport threadingimport timelogging.basicconfig (level=logging. DEBUG, format= ' (% (threadname) -10s)% (message) s ',) def lock_holder (lock): Logging.debug (' Start ing ') while True:lock.acquire () try:logging.debug (' Holding ') time.sleep (0.5) finally:logging.d  Ebug (' not Holding ') Lock.release () time.sleep (0.5) return DEF worker (lock): Logging.debug (' starting ') num_tries = 0 Num_acquires = 0 while num_acquires < 3:time.sleep (0.5) logging.debug (' Trying to acquire ') ha               Ve_it = Lock.acquire (0) Try:num_tries + = 1 if have_it:logging.debug (' Iteration%d:acquired ', num_tries) Num_acquires + = 1 else:logging.debug (' Iteration%d:not acquired ', Nu m_tries) finally:if have_it:lock.release () logging.debug (' Done after%d iterations ', num_tries) lock = th Reading. Lock () holder = threading.            Thread (Target=lock_holder, Args= (lock,), name= ' Lockholder ') Holder.setdaemon (True) holder.start () worker = Threading. Thread (Target=worker, args= (lock,), name= ' worker ') Worker.start ()

Execution Result:

$ python threading_lock_noblock.py

(Lockholder) Starting (Lockholder) Holding (worker  ) starting (Lockholder) not Holding (worker  ) Trying to acquire (worker  ) Iteration 1:acquired (Lockholder) Holding (worker  ) Trying to acquire (worker  ) Iteration 2:not acquired (lockhol der) Not holding (worker)  Trying to acquire (worker  ) Iteration 3:acquired (Lockholder) Holding (worker  ) Trying to acquire (worker  ) Iteration 4:not acquired (Lockholder) not holding (worker  ) Trying to acquire (worker
  ) Iteration 5:acquired (Worker  ) done after 5 iterations

Line Shuo Full lock

Threading. Rlock ()

Returns an Reentrant lock object. The re-entry lock must be freed by the thread that obtains it. Once a thread acquires a re-entry lock, it is obtained again without blocking, and must be released after fetching.

Usually a thread can only get one lock at a time:

Import Threadinglock = Threading. Lock () print ' first try: ', Lock.acquire () print ' Second try: ', Lock.acquire (0)

Execution Result:

$ python threading_lock_reacquire.py

First Try:truesecond Try:false

Multiple locks can be obtained using Rlock:

Import Threadinglock = Threading. Rlock () print ' first try: ', Lock.acquire () print ' Second try: ', Lock.acquire (0)

Execution Result:

Python threading_rlock.py

First Try:truesecond try:1

Let's look at one more example:

#!/usr/bin/env python3# coding=utf-8import threadingimport timeclass Box (object): Lock = Threading.    Rlock () def __init__ (self): self.total_items = 0 def execute (self,n): Box.lock.acquire () Self.total_items + = n    Box.lock.release () def add (self): Box.lock.acquire () Self.execute (1) Box.lock.release () def remove (self): Box.lock.acquire () Self.execute ( -1) Box.lock.release () # # These, functions run n separate## Threads and CA    ll the Box ' s Methods def Adder (Box,items): While Items > 0:print ("Adding 1 item in the box\n") Box.add () Time.sleep (5) Items-= 1 def remover (box,items): While Items > 0:print ("Removing 1 item in the box") Bo  X.remove () Time.sleep (5) Items-= 1 # # The main program build some## threads and make sure it worksif __name__ = "__main__": Items = 5 print ("Putting%s items in the box"% items) box = box () T1 = Threading. Thread (target=adder,args= (box,items)) t2 = Threading. Thread (target=remover,args= (Box,items)) T1.start () T2.start () T1.join () T2.join () print ("%s items still remain in the box"% box . Total_items)

Execution Result:

$ Python3 threading_rlock2.py

Putting 5 items in the box adding 1 item in the Boxremoving 1 item in the Boxadding 1 item in the Boxremoving 1 item in th E boxadding 1 Item in the Boxremoving 1 item in the Boxremoving 1 item in the Boxadding 1 item in the Boxremoving 1 item i n the boxadding 1 item in the box0 items still remain in the box
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.