Python thread Lock (thread) Learning example

Source: Internet
Author: User
Copy CodeThe code is as follows:


# Encoding:utf-8
Import Thread
Import time

# a function for executing in thread
def func ():
For I in range (5):
print ' func '
Time.sleep (1)

# End Current Thread
# This method is equivalent to Thread.exit_thread ()
Thread.exit () # When Func returns, the thread also ends

# Start a thread and the thread starts running immediately
# This method is equivalent to Thread.start_new_thread ()
# The first parameter is the method, the second argument is the parameter of the method
Thread.start_new (func, ()) # method requires an empty tuple when there are no arguments

# Create a lock (LockType, cannot be instantiated directly)
# This method is equivalent to Thread.allocate_lock ()
Lock = Thread.allocate ()

# Determine if the lock is locked or released
Print lock.locked ()

# locks are typically used to control access to shared resources
Count = 0

# get lock, return True when lock is successfully obtained
# The optional timeout parameter is blocked until the lock is obtained
# Otherwise the timeout will return false
If Lock.acquire ():
Count + = 1

# release Lock
Lock.release ()

# threads provided by the thread module will end at the end of the main thread
Time.sleep (6)

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

Thread also provides a threadlocal class for managing thread-related data, called thread._local,threading, which refers to this class.

  • 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.