A thread can be created, ready, running, blocked, or killed in five states. There are three cases of blocking: synchronous blocking refers to the status in which the thread requests to lock will enter this status at a scheduled time. once the lock is obtained successfully, it will be restored to the running status; waiting for blocking refers to the status of waiting for notifications from other threads. after the thread obtains the condition lock, the "waiting" call will enter this status. once other threads send a notification, the thread will enter the synchronous blocking status, when the competition condition is locked again, other blocking means the call time. sleep (), anotherthread. join (... the thread has five states.
New, ready, running, blocking, and dead.
There are three blocking situations:
Synchronization blocking refers to a state in which a thread requests a lock and enters this state at regular intervals. once the lock is obtained successfully, the thread returns to the running state;
Waiting for blocking refers to the status of waiting for notifications from other threads. after the thread obtains the condition lock, the "waiting" call will enter this status. once other threads send a notification, the thread will enter the synchronous blocking status, again, the competition conditions are locked;
Other blocking means the blocking of calling time. sleep (), anotherthread. join () or waiting for IO. in this state, the thread will not release the obtained 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']
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']
>>> 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']
Common methods provided by the threading module:
Threading. currentThread (): returns the current thread variable.
Threading. enumerate (): returns a list containing running threads. Running means that the threads before and after startup and termination are not included.
Threading. activeCount (): returns the number of running threads, with the same results as len (threading. enumerate.
Inherit the threading. Thread method and override the run method.
Threading. Thread class initialization function prototype: def _ init _ (self, group = None, target = None, name = None, args = (), kwargs = {})
The group parameter is reserved for future expansion;
The target parameter is a Callable object (also called an activity) that is executed after the thread starts;
The parameter name is the name of the thread. The default value is "Thread-N", and N is a number.
The args and kwargs parameters represent the parameter list and keyword parameters when the target is called, respectively.
Join () method. the Thread that calls this method will wait until the Thread object is completed and resume running.
Calling Thread. join will block the main Thread until the call Thread ends or times out. The timeout parameter is a numeric value that indicates the timeout time. if this parameter is not provided, the main thread will be blocked until the end of the called thread.
Threading. Lock object: mutex, which has the acquire () and release () methods.
RLock allows multiple acquire requests in the same thread. But Lock does not allow this situation. Note: If RLock is used, The acquire and release must appear in pairs. that is, The acquire and release must be called n times to release the occupied space.
Threading. Condition object: condition variable. when this object is created, it will contain a Lock object (because condition variable is always used with mutex ). You can call the acquire () and release () methods on the Condition object to control the potential Lock object.
Condition. wait ([timeout]): The wait method releases the cumbersome internal occupation, and the thread is suspended until the notification is awakened or timed out (if the timeout parameter is provided ). When the thread is awakened and occupied again, the program will continue to run.
Condition. Condition Y (): wake up a suspended thread (if a suspended thread exists ). Note: The notify () method does not release the occupied objects.
Condition. policyall () wake up all suspended threads (if a suspended thread exists ). Note: these methods do not release the occupied items.