Python Process related-multithreaded threading library

Source: Internet
Author: User

Concept

Multithreading is similar to executing several different programs at the same time.

Advantages

Threads can be used to place tasks that occupy a long period of time in the background to be processed.

User interface can be more attractive, such as the user clicked a button to trigger the processing of certain events, you can pop up a progress bar to show the progress of processing

The program may run faster

Threads are useful for tasks such as user input, file read and write, and network send and receive data. In this case we can release some precious resources such as memory footprint and so on.

Basic knowledge

Threads are still different from the process during execution. each separate thread has a program run entry, sequence of sequence execution, and exit of the program. However, threads cannot be executed independently and must be dependent on the application (process) , which provides multiple threads for execution control.

Each thread has his own set of CPU registers, called the thread's context, which reflects the state of the CPU register on which the thread last ran the thread.

The instruction pointer and stack pointer registers are the two most important registers in the thread context, and threads are always run in the context of the process, which is used to flag memory in the process address space of the owning thread.

The thread can be preempted (interrupted).

Threads can be shelved (also known as sleep) while other threads are running-this is the thread's retreat.

Threads can be divided into

Kernel thread: Created and revoked by the operating system kernel.

User thread: A thread implemented in a user program that does not require kernel support.

multithreaded modules in the Python3

_thread (for compatibility with Python2)

Threading (recommended)

Multi-threaded use of Python

Reference links

Http://www.cnblogs.com/vamei/archive/2012/10/11/2720042.html

There are two ways to use threads in Python: A function or a class to wrap a thread object.

Functional _thread modules (not normally used)

Start_new_thread () function to generate a new thread

Threading Module

Start_new_thread () function to generate a new thread

CurrentThread (): Returns the current thread variable.

Enumerate (): Returns a list that contains the running thread. Running refers to threads that do not include pre-and post-termination threads until after the thread has started and ends.

Activecount (): Returns the number of running threads with the same result as Len (Threading.enumerate ()).

Threading. Thread class Encapsulation Threading usage method

It is generally a custom class that inherits from Threading. Thread class, so that we can only implement the method of that class.

Threading. Methods in the Thread class

Run (): The method used to represent thread activity.

Start (): Initiates thread activity.

Join ([TIME]): The current thread waits for the thread object to abort.

such as Thread_a.join () indicates that the current thread will be blocked until the thread_a thread is called abort/Normal exit/Throw exception/timeout.

IsAlive (): Returns whether the thread is active.

GetName (): Returns the thread name.

SetName (): Sets the thread name.

Exit (): The end of a thread is generally dependent on the natural end of the thread function, or thread.exit () can be called in an inline function, and he throws Systemexit exception to exit the thread.

Thread synchronization reference links in the threading library

Http://www.cnblogs.com/vamei/archive/2012/10/11/2720042.html

Issues to be aware of

if the shared resource you want to use is an immutable data type, you must add global to the global variable, or, if it is a mutable data type, store the data type in the heap

Mutex lock Threading. Lock Object

Get Mutex: Lock = threading. Lock ()

Apply for Mutex: Lock.acquire ()

Unlock Mutex: Lock.release ()

The condition variable threading. Condition Object

When the object is created, it contains the creation of a lock object

Create condition Variable object: conf = Threading. Condition ()

Apply for Mutex: Conf.acquire ()

Unlock Mutex: Conf.release ()

Multiple threads Waiting: conf.wait ()

Notifies all waiting threads to start working: Conf.notify_all ()

Notifies the specified thread to start working: Conf.notify ()

Thread Count lock Threading. Semaphore Object

There are two ways to apply for mutexes and unlock mutexes

Thread event Threading. Event Object

Threading.condition objects similar to lock-free protection

The Evnetn object has a true and false two states, wait () is set to false, the process waits, and sets () sets to true so that all waiting states begin to work.

Create thread Event object: Event = Threading. Event ()

Multiple threads Waiting: event.wait ()

Notifies all waiting threads to start working: Event.set ()

Notifies all event types of thread waits: Event.clear ()

Application scenarios are temporarily unclear

Thread Queues Queue Reference link

Http://www.runoob.com/python3/python3-multithreading.html

Content

Primarily includes FIFO (first-in, first-out) queue Queue,lifo (back-in first-out) queue Lifoqueue, and priority queue priorityqueue.

These queues implement the lock primitive and can be used directly in multiple threads, and queues can be used to synchronize between threads.

Common methods in the Queue module

Queue.qsize () returns the size of the queue

Queue.empty () returns True if the queue is empty, and vice versa false

Queue.full () returns True if the queue is full, otherwise false

Queue.full corresponds to maxsize size

Queue.get ([block[, timeout]]) Get queue, timeout wait time

Queue.get_nowait () quite queue.get (False)

Queue.put (item) write queue, timeout wait time

Queue.put_nowait (item) quite Queue.put (item, False)

Queue.task_done () After completing a work, the Queue.task_done () function sends a signal to the queue that the task has completed

Queue.join () actually means waiting until the queue is empty before performing another operation

Python Process related-multithreaded threading library

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.