Python thread and process notes

Source: Internet
Author: User
Tags mutex thread class

#线程应用的第一种方式: 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

#线程应用的第二种方式: Threading module is a thread that has been packaged to make it easier to reference
#import Threading: Referenced modules
#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.
#class MyThread (Threading. Thread): Create the object of the class
#可以进行重构函数的对应扩展: Def __init__ (self,name,time): Threading. thread.__init__ (self,name= ' corresponding thread name ')
#myThread =mythread (): Creating an Object
#myThread. Start (): Thread starts execution

Mutex------------------------------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.

#mutex =threading. Lock (): Create Mutex
#if Mutex.acquire ([blocking]): Mutex lock state, return value not 0 indicates successful lockout
#锁定方法acquire可以有一个blocking参数. If the 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 status

------------------------------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: Make a reference to the corresponding queue package
#queue =queue (): Queue creation
#queue. Qsize (): Gets the number of content in the queue
#queue. Put (content): Add corresponding data information to the queue
#queue. Set (): Remove the corresponding data from the queue
#queue. Empty (): To see if the contents of the current queue are empty

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

#event =threading. Event (): Create the corresponding Envent object
#self. Threadevent=event: Refactor the corresponding threading. The __init__ method in the thread base class.
#self. Threadevent.wait (): Put threads into a wait state
#event. Set (): Start the waiting thread 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

Global_dict[threading.current_thread ()]

In the Unix/linux operating system, a fork () system function is provided, which is very special.

A normal function call, 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 always returns 0, 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: Referencing the corresponding process package

#pid =os.fork (): When the program executes to Os.fork (), the operating system creates a new process (child process), then copies all the information of the parent process into the child process, and then the parent and child processes get a return value from the fork () function, which must be a value of 0 in the process. And the ID number of the child process in the parent process

#os. Getpid (): Gets the PID of the current process
#os. Getppid (): Gets the PID of the parent process

------------------------------Multiprocessing Module---------------------------
#from the multiprocessing Import 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 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 number of CPU cores
#pipe =multiprocessing. Pipe (): Create a pipeline with two ports called Pipe[0],pipe[1]
#pipe [0].send (i): adding content to the pipeline 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: 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.