Python thread lock of thread learning example

  • 2020-04-02 13:18:44
  • OfStack


# encoding: UTF-8
import thread
import time

#  A function that executes in a thread 
def func():
    for i in range(5):
        print 'func'
        time.sleep(1)

    #  End the current thread 
    #  This method is associated with thread.exit_thread() equivalent 
    thread.exit() #  when func When it returns, the thread also ends 

#  Start a thread and the thread starts running immediately 
#  This method is associated with thread.start_new_thread() equivalent 
#  The first parameter is the method, and the second parameter is the method's parameter 
thread.start_new(func, ()) #  Null is passed in when the method has no arguments tuple

#  Create a lock ( LockType , cannot be instantiated directly) 
#  This method is associated with thread.allocate_lock() equivalent 
lock = thread.allocate()

#  Determines whether a lock is locked or released 
print lock.locked()

#  Locks are often used to control access to Shared resources 
count = 0

#  Lock is obtained and returned after successful lock acquisition True
#  optional timeout If the parameter is not filled, it will block until the lock is obtained 
#  Otherwise a timeout is returned False
if lock.acquire():
    count += 1

    #  Release the lock 
    lock.release()

# thread All threads provided by the module will terminate at the same time as the main thread 
time.sleep(6)

Additional methods provided by the thread module:
Thread.interrupt_main (): terminates the main thread in another thread.
Thread.get_ident (): gets a magic number representing the current thread, often used to get thread-specific data from a dictionary. The number itself has no meaning and is reused by new threads when the thread ends.

Thread also provides a ThreadLocal class for managing thread-related data, named thread._local, which is referenced in threading.


Related articles: