Copy codeThe Code is as follows:
# Encoding: UTF-8
Import thread
Import time
# A function used for execution in a thread
Def func ():
For I in range (5 ):
Print 'func'
Time. sleep (1)
# End the current thread
# This method is equivalent to thread. exit_thread ().
Thread. exit () # When func returns, the thread will also end
# Start a thread and the thread starts running immediately
# This method is equivalent to thread. start_new_thread ().
# The first parameter is the method, and the second parameter is the method parameter.
Thread. start_new (func, () # When there is no parameter in the method, a blank tuple is required.
# Create a lock (LockType, cannot be directly instantiated)
# This method is equivalent to thread. allocate_lock ().
Lock = thread. allocate ()
# Determine whether the lock is locked or released
Print lock. locked ()
# A lock is usually used to control access to shared resources.
Count = 0
# Obtain the lock. If the lock is successfully obtained, True is returned.
# When the optional timeout parameter is not set, it will be blocked until it is locked.
# Otherwise, False will be returned after the timeout
If lock. acquire ():
Count + = 1
# Release a lock
Lock. release ()
# All threads provided by the thread module end simultaneously after the main thread ends.
Time. sleep (6)
Other methods provided by the thread module:
Thread. interrupt_main (): Terminate the main thread in other threads.
Thread. get_ident (): obtains a magic number that represents the current thread. It is often used to obtain thread-related data from a dictionary. This number has no meaning, and will be reused by the new thread after the thread ends.
Thread also provides a ThreadLocal class for managing thread-related data, named thread. _ local, which is referenced in threading.