Home Backend Development Python Tutorial Python thread sorting

Python thread sorting

Dec 09, 2016 pm 02:11 PM
python

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.



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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Can the Python interpreter be deleted in Linux system? Can the Python interpreter be deleted in Linux system? Apr 02, 2025 am 07:00 AM

Regarding the problem of removing the Python interpreter that comes with Linux systems, many Linux distributions will preinstall the Python interpreter when installed, and it does not use the package manager...

How to solve the problem of Pylance type detection of custom decorators in Python? How to solve the problem of Pylance type detection of custom decorators in Python? Apr 02, 2025 am 06:42 AM

Pylance type detection problem solution when using custom decorator In Python programming, decorator is a powerful tool that can be used to add rows...

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

Python 3.6 loading pickle file error ModuleNotFoundError: What should I do if I load pickle file '__builtin__'? Python 3.6 loading pickle file error ModuleNotFoundError: What should I do if I load pickle file '__builtin__'? Apr 02, 2025 am 06:27 AM

Loading pickle file in Python 3.6 environment error: ModuleNotFoundError:Nomodulenamed...

Do FastAPI and aiohttp share the same global event loop? Do FastAPI and aiohttp share the same global event loop? Apr 02, 2025 am 06:12 AM

Compatibility issues between Python asynchronous libraries In Python, asynchronous programming has become the process of high concurrency and I/O...

What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6? What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6? Apr 02, 2025 am 07:12 AM

Error loading Pickle file in Python 3.6 environment: ModuleNotFoundError:Nomodulenamed...

How to ensure that the child process also terminates after killing the parent process via signal in Python? How to ensure that the child process also terminates after killing the parent process via signal in Python? Apr 02, 2025 am 06:39 AM

The problem and solution of the child process continuing to run when using signals to kill the parent process. In Python programming, after killing the parent process through signals, the child process still...

See all articles