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']
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 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.

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment