Python network programming (process communication, signal, wire lock, multithreading)

Source: Internet
Author: User
Tags semaphore terminates thread class

what is a signal for process communication?
we all know that with windows, when we can't end a program properly, we can force this process to end with the task manager, but how does it work? The same functionality is achieved on Linux by generating signals and capturing signals, and the running process captures the signal and then makes certain operations and ends up being terminated. The signal is an event that occurs when UNIX and Linux systems respond to certain conditions, and the process that receives the signal takes some action accordingly. Usually the signal is generated by an error. However, they can also be used as a way to communicate or modify behavior between processes, explicitly sent to another process by one process. The generation of a signal is called generating, receiving a signal called capture
what is a thread lock? 1. In the case of a single process can be called a single process can also be called one-thread 2. The general idea of the thread lock is that if thread A and thread B execute two functions A and B, if a must be run before B, then B will be allowed to enter wait when B enters the B function.

Set until a executes the a function and then activates B from the wait set. This ensures that B must be run after a, regardless of the order in which they were previously sequenced.

3. The thread lock is used for scheduling of multiple threads that must be executed in a fixed order

The idea of the thread lock is to lock the post-order thread first, and then let the line-ordering thread complete the task and then unlock the post-thread.

Signal:A process transmits a message by means of a signal, and the receiving party receives the signal and makes corresponding processingKill-sig pid: Kills the specified process by sending a signal via PIDkill-l: View all in the operating systemSigSignal: Signal Name: System definition, name or digital signal meaning: System definition, function of the signal default processing method: When a process receives a signal, the effect process terminates by default, pauses the process, ignores the method occurs SIGHUP: Break link Sigint:ctrl + C Sigquit:ctrl + \ Sigtstp:ctrl + z SIGKILL: Terminates the process and cannot be processed SIGSTOP: pauses the process and cannot Processed SIGALRM: Clock signal SIGCHLD: When a child process changes state, the parent process receives this signal Python signal processing: (signal module)Os.kill(pid,sig) function: Send a signal to a process parameter: PID: Send signal to that process (process PID) SIG: The type of signal to sendSignal.alarm(SEC) Function: Asynchronous execution set the clock signal to send itself a SIGALRM signal after a certain time a process can only suspend a clock re-suspend the clock will overwrite the previous clock parameter: sec: Time (seconds)Signal.pause() function: block process, wait for a signalsignal.signal(sig,handler) function: Signal processing parameters: SIG: Signals to be processed handler: Signal processing method Optional value: SIG_DFL means that the default method is used to process the sig_ign indicating that the signal is ignored Func Custom Function Custom Function format: def func (Sig,frame): SIG: Received signal frame: signal structure object The signal function is also an asynchronous processing function, as long as the execution The function will be processed at any time to receive the corresponding signal will handle signal is not able to handle Sigkill, sigstop parent process can use signal (sigchld,sig_ign) to leave the child process exit to the system handlerAsynchronousAndSyncExecute: (synchronous asynchronous) synchronization of a single process: The program executes step-by-step, presenting a sequential sequence of asynchrony: The signal is the only internal communication method The program performs the necessary auxiliary operations with the help of the kernel function without affecting the application The continuous execution signal of the layer is an asynchronous example of an interprocess communication method:
 fromSignalImport*Import TimedefHandler (Sig,frame):#Custom Processing signals    ifsig = = Sigalrm:#Judging signal Types        Print("Receive clock signal")    elifsig = =SIGINT:Print("It doesn't end a little bit ~") Alarm (5)#set the 5-second clock signalsignal (Sigalrm,handler) signal (Sigint,handler)#Ctrl + C whileTrue:Print("waiting for a signal") Time.sleep (2)

Signal Volume:Given a certain quantity, it is visible to multiple processes, and multiple processes determine different behavior based on how much the semaphore is SEM =Semaphore(num) function: Create semaphore parameter: Semaphore initial value return value: Semaphore object SEM.Acquire() reduce the number of signals by 1 when the number is 0 o'clock block SEM.Release() Increase the signal volume by 1 SEM.Get_value() Gets the value of the current semaphore (quantity)Synchronous Mutex mechanismObjective: To solve the resource contention for shared resources critical resource: A resource critical section that can be manipulated by multiple processes or threads:code snippet for manipulating critical resourcesSynchronization: Synchronization is a cooperative relationship, in order to complete a task, a multi-process or multiple threads formed between a coordination according to the Convention, mutual notification, mutual completion of the task mutually exclusive: mutual exclusion is a restrictive relationship, when a process or thread into the critical section of the operation of resources in a locked way to prevent other Until unlocked to make a resourceEvent Events: fromMultiprocessingImportEvent Creation Events Object E =Event() event blocking E.wait([timeout]) feature: Causes the process to be blocked until the event object is set by the set event: E.Set. () function: Let the event object become set state clear setting: E.Clear() function: Make event object clear set State event judge: E.is_set () to determine whether the current event is set example:
 fromMultiprocessingImportprocess,event fromTimeImportSleepdefwait_event (file):Print("prepare to operate critical resources") e.wait ()#wait for the main process to finish executing the set    Print("start operation of critical resources", E.is_set ()) FW= Open ('1.jpg','WB') with open (file,'RB') as F:#Copy PictureFw.write (F.read ())defwait_event_timeout (file):Print("also want to operate critical resources") e.wait (2)#waits for the main process to execute set and 2-second timeout detection    ifE.is_set ():Print("also started to operate critical resources") FW= Open ('2.jpg','WB') with open (file,'RB') as F:#Copy PictureFw.write (F.read ())Else:        Print("It 's not going to wait .")#Create EventE =Event () path="/home/tarena/file.jpg"file='file.jpg'#Create two processes to copy two images separatelyP1 = Process (target = Wait_event,args =(file,)) P2= Process (target = Wait_event_timeout,args =(file,)) P1.start () P2.start ( )#The main process first copies the picture so that the child process enters the wait statePrint("The main process is operating critical resources") Sleep (3) FW= Open (file,'WB') with open (path,'RB') as F:fw.write (F.read ()) Fw.close () E.set ()#Child process SetPrint("The main process has finished operation") P1.join () P2.join ()



Lock lookMultiprocessing--Look Create object: Lock =Lock() lock.Acquire()lockedLock.Release()UnlockIf a lock object has been locked and then called then it will block multiprocessing created by the child process cannot use input to error example:
 fromMultiprocessingImportProcess,lockImportSYS fromTimeImportSleep#Sys.stdout as a standard output stream is a resource common to multiple processesdefwriter1 (): Lock.acquire ()#locked     forIinchRange (5): Sleep (1) Sys.stdout.write ("writer1 output \ n") lock.release ()#Unlock#It's sleep1 seconds, but it prints two times every 1 seconds without locking .#because of the lock reason W1 executes the critical section W2 to be executed one seconddefWriter2 (): With Lock: forIinchRange (5): Sleep (1) Sys.stdout.write ("writer2 output \ n")#Create a lockLock =Lock () W1= Process (target =writer1) W2= Process (target =writer2) W1.start () W2.start () W1.join () W2.join ()



Multithreading:What is a thread (ThreadThreads are also a multi-tasking approach that can use the computer's multicore resource threads that are called lightweight process thread features: 1. A process canincludeMultiple threads 2. Threads are the smallest unit 3 used by the computer kernel. Threads are also a running process and consume computer resources 4. Multiple threads share resources for a pooled process 5. Threads also have their own feature attributes, TID, instruction set, thread stack 6. Multiple threads Independent non-interference space (both consume process space) 7. Thread creation Delete consumes less resources than process threads/processes (1/20) Threading module threshold.Thread() function: Create thread object parameter: Target thread function name line Cheng think Thread-1 ... the args tuple gives the thread function positional arguments Kwarg The s dictionary gives the thread function key value to the parameter return value: Thread Object T.start () starts thread t.join () reclaims thread thread object properties: T.nameThe thread name T.SetName() sets the thread name T.is_alive ()View Thread state Threading.CurrentThread() Gets the current Process object T.daemon property by default, the exit of the main thread does not affect the execution of the sub-route is set to True when the main thread exits the branch path and also exits the set daemon value T.Setdaemon(True) T.Daemon= True to view the daemon value T.IsdaemonCreate your own thread class; 1. Inherit thread 2. Load Parent class__init__3. RewriteRunExample:
 fromThreadingImportThread fromTimeImportSleep, CTime#Create a Mythread class to inherit the threadclassMyThread (Thread):def __init__(self, target, name ="tedu", args = (), Kwargs ={}): Super ().__init__()#Reload the __init__ initialization method of the parent classSelf.target =Target Self.name=name Self.args=args Self.kwargs=KwargsdefRun (self):#call the Run method automatically when you create an object#The thread function to be executed in the call to run Si Cho is to receive a universal pass in the form of a tuple and a dictionarySelf.target (*self.args, * *Self.kwargs)#Thread Functionsdefplayer (song,sec): forIinchRange (2):        Print("Playing%s:%s"%(song, CTime ())) Sleep (sec)#creates a thread with a custom class and executest = MyThread (target = player, args = ("calories", 3)) T.start () T.join ()


Python network programming (process communication, signal, wire lock, multithreading)

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.