Home > Backend Development > Python Tutorial > Python thread sorting

Python thread sorting

巴扎黑
Release: 2016-12-09 14:11:47
Original
1503 people have browsed it

Threads have five states

New, ready, running, blocked, and dead.

There are three situations of blocking:

Synchronous blocking refers to the state of competing locks. A thread will enter this state when requesting a lock. Once the lock is successfully obtained, it will return to the running state;

Waiting blocking refers to waiting for notification from other threads. state, after the thread obtains the conditional lock, calling "wait" will enter this state. Once other threads send notifications, the thread will enter the synchronous blocking state and compete for the conditional lock again;

And other blocking refers to calling time.sleep(), anotherthread .join() or blocking while waiting for IO. In this state, the thread will not release the acquired lock.



Python provides two ways to use threads, one is functional and the other is class packaging.

* thread
* threading

1. Thread:

>>> import thread
>>> dir(thread)
['LockType', '__doc__', '__name__', '__package__', '_count', '_local', 'allocate', 'allocate_lock', 'error', 'exit', 'exit_thread', 'get_ident', 'interrupt_main', 'stack_size', 'start_new', 'start_new_thread']
Copy after login

thread.start_new_thread ( function , args [ , kwargs ] )
Call the start_new_thread() function in the thread module to generate a new thread.

2. Threading:

>>> import threading
>>> dir(threading)
['BoundedSemaphore', 'Condition', 'Event', 'Lock', 'RLock', 'Semaphore', 'Thread', 'ThreadError', 'Timer', '_BoundedSemaphore', '_Condition', '_DummyThread', '_Event', '_MainThread', '_RLock', '_Semaphore', '_Timer', '_VERBOSE', '_Verbose', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_active', '_active_limbo_lock', '_after_fork', '_allocate_lock', '_counter', '_enumerate', '_format_exc', '_get_ident', '_limbo', '_newname', '_pickSomeNonDaemonThread', '_profile_hook', '_shutdown', '_sleep', '_start_new_thread', '_sys', '_test', '_time', '_trace_hook', 'activeCount', 'active_count', 'currentThread', 'current_thread', 'deque', 'enumerate', 'local', 'setprofile', 'settrace', 'stack_size', 'warnings']
Copy after login
>>> dir(threading.Thread)
['_Thread__bootstrap', '_Thread__bootstrap_inner', '_Thread__delete', '_Thread__exc_clear', '_Thread__exc_info', '_Thread__initialized', '_Thread__stop', '__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_block', '_note', '_reset_internal_locks', '_set_daemon', '_set_ident', 'daemon', 'getName', 'ident', 'isAlive', 'isDaemon', 'is_alive', 'join', 'name', 'run', 'setDaemon', 'setName', 'start']
Copy after login

Common methods provided by the threading module:

threading.currentThread(): Returns the current thread variable.

threading.enumerate(): Returns a list containing running threads. Running refers to after the thread starts and before it ends, excluding threads before starting and after termination.

threading.activeCount(): Returns the number of running threads, which has the same result as len(threading.enumerate()).



Inherit the threading.Thread method and override the run method.

Initialization function prototype of threading.Thread class: def __init__(self, group=None, target=None, name=None, args=(), kwargs={})
 The parameter group is reserved for future expansion ;
 The parameter target is a callable object (also called activity [activity]), which is executed after the thread is started;
 The parameter name is the name of the thread. The default value is "Thread-N", where N is a number.
 The parameters args and kwargs respectively represent the parameter list and keyword parameters when calling target.


join() method, the thread calling this method will wait until the Thread object is completed and then resume running.
Calling Thread.join will block the calling thread until the called thread ends or times out. The parameter timeout is a numeric type, indicating the timeout time. If this parameter is not provided, the calling thread will be blocked until the called thread ends.

threading.Lock object: mutex, has acquire() and release() methods

RLock allows to be acquired multiple times in the same thread. But Lock does not allow this. Note: If RLock is used, acquire and release must appear in pairs, that is, acquire is called n times, and release must be called n times to truly release the occupied lock.

Threading.Condition object: condition variable. When this object is created, it will contain a Lock object (because condition variable is always used together with mutex). The acquire() and release() methods can be called on the Condition object to control potential Lock objects.

Condition.wait([timeout]): The wait method releases the internal memory occupied, and the thread is suspended until it is awakened after receiving a notification or times out (if the timeout parameter is provided). When the thread is awakened and reoccupies the thread, the program will continue to execute.

Condition.notify(): Wake up a suspended thread (if there is a suspended thread). Note: The notify() method will not release the occupied memory.

Condition.notifyAll() Wake up all suspended threads (if there are suspended threads). Note: These methods do not release the occupied memory.



Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template