Python thread Lock (thread) Learning example _python

Source: Internet
Author: User

Copy Code code as follows:

# Encoding:utf-8
Import Thread
Import time

# a function to be executed in a 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 will also end

# Start a thread, 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 parameter of the method
Thread.start_new (func, ()) # method requires incoming NULL when no parameters are available tuple

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

# to determine whether the lock is locked or released
Print lock.locked ()

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

# Acquire Lock, return true after successful lock acquisition
# Optional Timeout parameter will block until lock is not filled
# Otherwise the timeout will return false
If Lock.acquire ():
Count + 1

# release Lock
Lock.release ()

# The threads provided by the thread module will end at the same time as the main thread ends
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 will be reused by the new thread when the thread is finished.

Thread also provides a threadlocal class for managing thread-related data, which is referenced in the name thread._local,threading.

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.