Python thread learning example

Source: Internet
Author: User

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.

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.