Python thread and process notes

Source: Internet
Author: User
Tags mutex thread class

------------------------------Thread---------------------------
#线程应用的第一种方式: The thread module is the lower-level module
#import Thread: Referenced module
#thread. Start_new_thread (Defname, ()): Thread creation
#thread. Exit_thread (): End of Thread

#线程应用的第二种方式: The threading module is a wrapper over the thread that makes it easier to refer to
#import threading: The referenced module
#myThread =threading. Thread (target=defname,args= (' Alice ',)): Creation of Threads
#myThread. Start (): Thread starts execution
#num =len (threading.enumerate) : View of the number of threads
#线程应用的第三种方式: Create a thread class that inherits the base class: Threading. Thread. Rewrite def run (self): method. The content that needs to be run is written in the Run method. The
#class MyThread (threading. Thread): Creates the object of the class
#可以进行重构函数的对应扩展: Def init (self,name,time): Threading. Thread. Init (self,name= ' corresponding thread name ')
#myThread =mythread (): Create Object
#myThread. Start (): Thread starts execution
------------------------------ The mutex for thread synchronization---------------------------
#线程同步之互斥锁
#互斥锁同步: Thread synchronization guarantees multiple threads secure access to competing resources, and the simplest synchronization mechanism is to reference mutexes. A mutex introduces a state to a resource: locked/non-locked. When a thread changes the shared data, it locks it, the state of the resource is locked, the other thread cannot be changed, and until the thread frees the resource, the state of the resource becomes "non-locked", and the other thread can lock the resource again. The
#mutex =threading. Lock (): Create Mutex
#if mutex.acquire ([blocking]): Mutex lock state, return value not 0 means lockout successful
# Lock method acquire can have a blocking parameter. If blocking is set to true, the current thread is blocked until the lock is acquired (true if not specified), and if set blocking is false, the current thread does not block
# Mutex.release (): Mutex release State

------------------------------thread is synchronized to a reentrant lock---------------------------
#线程同步之可重入锁
#RLock内部维护着一个Lock和一个counter变量, counter records the number of acquire, so that resources can be acquire multiple times. Until all the acquire of a thread are release, the other threads can get the resources:
#mutex =threading. Rlock (): Create a reentrant lock
#mutex. Acquire (): Can be re-entered lock lock status
#mutex. Release (): Can be re-entered lock release status
------------------------------The condition variables for thread synchronization---------------------------
#线程同步之条件变量
#Python提供的Condition对象提供了对复杂线程同步问题的支持. condition is called a conditional variable and provides the wait and notify methods in addition to the acquire and release methods similar to lock. The thread first acquire a condition variable and then determines some conditions. Wait if the condition is not met, and if the condition is met, after some processing changes the condition, the other thread is notified by the Notify method, and the other thread in the wait state will be re-judged after receiving the notification. Constantly repeating this process to solve complex synchronization problems.
#Condition对象维护了一个锁 (Lock/rlock) and a waiting pool. The thread obtains the condition object through acquire, and when the wait method is called, the thread releases the lock inside the condition and enters the blocked state while recording the thread in the waiting pool. When the Notify method is called, the condition object picks a thread from the waiting pool and notifies it to invoke the Acquire method to fetch the lock.
The/rlock object is #Condition对象的构造函数可以接受一个Lock as a parameter, and if not specified, the condition object creates an internal rlock on its own.
#除了notify方法外, the Condition object also provides a Notifyall method that notifies all threads in the waiting pool to attempt to acquire an internal lock. As a result of the above mechanism, threads in the waiting state can only be awakened by the Notify method, so the role of notifyall is to prevent the thread from ever being in a state of silence.
#con =threading. Condition (): Create condition variable
#con. Acquire (): Conditional variable lock state
#con. Wait (): thread frees condition internal locks and enters blocked state while recording this thread in the waiting pool
#con. Notify (): The Condition object picks a thread from the waiting pool and notifies it to call the acquire method to try to fetch the lock
#con. Notifyall (): Wakes all threads in the waiting pool, preventing thread threads from ever being silent
#con. Release (): Conditional variable release status

Queue------------------------------thread synchronization---------------------------
#from Queue Import Queue: reference to the corresponding queue package
# Queue=queue (): Queue creation
#queue. Qsize (): Gets the number of contents in the queue
#queue. Put (content): Adds the corresponding data information
#queue to the queue. Set (): fetches the corresponding data from the queue
#queue. Empty (): To see if the current queue content is empty
thread queue implementation producer consumer
------------------------------ Inter-thread communication---------------------------
Threading. An event can cause a thread to wait for notifications from other threads. It has a built-in flag with an initial value of false. The thread enters the wait state through the wait () method until another thread calls the set () method to set the built-in flag to true when the event notifies all waiting-state threads to resume running. You can also query the current value of the built-in state of the Envent object by using the Isset () method. The
#event =threading. Event (): Creates a
#self for the corresponding Envent object. Threadevent=event: Refactoring corresponds to threading. Method of Init in the thread base class.
#self. threadevent.wait (): Causes the thread to enter a wait state
#event. Set (): Starts the thread waiting in the waiting pool

Merge and background threads for------------------------------threads---------------------------
The join () method is also available in the thread class of Python so that one thread can wait for another thread to execute before it runs. This method can also set a timeout parameter to avoid endless waiting. Because two threads are finished sequentially, it looks like a thread, so it is called a merge of threads.
By default, the main thread waits for the end of all child threads when exiting. If you want the main thread to not wait for a child thread, but to automatically end all of the child threads on exit, you need to set the child thread to be a background thread (daemon). The method is by calling the Setdaemon () method of the thread class.
#myThread. Setdaemon (True): Convert this thread to a background thread

------------------------------ThreadLocal---------------------------
global_dict={}
Global_dict[threading.current_thread ()]

------------------------------Multi-process---------------------------
provides a fork () system function in the Unix/linux operating system, which is very special. The
normal function call, which is called once, is returned once, but the fork () is called once and returned two times because the operating system automatically copies the current process (called the parent process), which is then returned within the parent and child processes, respectively. The
child process returns 0 forever, and the parent process returns the ID of the child process.
The reason for this is that a parent process can fork out many child processes, so the parent process has to note the ID of each child process, and the child process only needs to call Getppid () to get the ID of the parent process.
#import OS: reference the corresponding process package
#pid =os.fork (): When the program executes to Os.fork (), the operating system creates a new process (the child process), then copies all the information of the parent process into the child process, and then the parent and child processes are all from the fork () function to get a return value, in which the value must be 0, and the parent process is the child process ID number
#os. Getpid (): Gets the PID
#os of the current process. Getppid (): Gets the PID
--------------of the parent process ----------------multiprocessing Module---------------------------
#from multiprocessing Import The Process:multiprocessing module provides a process class to represent a processing object.
#p =process (target=run_proc,args= (' Test ')): Create the corresponding Process object
#p. Start (): Start of the process
#p. Join () : The multiprocessing module provides a process class to represent a processing object, and the following example demonstrates starting a child process and waiting for it to end
#multiprocessing. Cpu_count (): View the corresponding CPU cores
# Pipe=multiprocessing. Pipe (): Create a pipeline with two ports called Pipe[0],pipe[1]
#pipe [0].send (i): adding content to the pipe side
#pipe [0].recv (): Get content information on the side of the pipeline

Python thread and process notes

Related Article

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.