The 11th chapter of the Python basics thread, process, and association

Source: Internet
Author: User
Tags semaphore

One, thread

The previous article already outlines what threads are and how threads work, multithreading, and process relationships are summarized as follows:

    • A thread is the smallest execution unit, and the process consists of at least one thread;
    • Process and thread scheduling, complete with the operating system decision, the program can not determine when to execute and how long to execute .
    • An application can have multi-process, multi-threaded
    • The default is single-process, single-threaded
    • Single-process, multi-threading, no performance gains in Python, can be promoted in Java and C #
    • Multithreading: IO operations are dense, generally do not use the CPU, efficiency improvement is possible
    • Multi-process: computationally intensive, requires CPU usage, so performance is not improved

The concept says a lot below to point the actual, code!

To create a thread:

Import Threading def F1 (ARG):     Print (ARG) t=threading. Thread (target=f1,args= (123,)) T.start ()   

It's simple. This is to create a thread, or you can inherit a thread, create it Yourself

classMyThread (Threading. Thread):#create a class yourself, inheriting threading. Thread)    def __init__(Self,func,args): Self.func=func Self.args=args Super (mythread,self).__init__()#executes the constructor of the Mythread parent class        defRun (self):#then define a run method yourselfSelf.func (Self.args)#Execute the F2 functiondefF2 (ARG):Print(ARG) obj=mythread (f2,123)#Pass in the parameters .Obj.start ()#Start Thread

Threading Common methods:

Threading.current_thread () returns the current thread variable.
Threading.enumerate () returns a list of running threads that are running after the thread has started, before the end, excluding pre-and post-termination threads.
Threading.active_count () returns the number of running threads, as with Len (Threading.enumerate ()).

Thread

Thread is a threading class, similar to Java, with two ways of using it, passing directly to the method to be run or inheriting from thread and overwriting run ().

The run () method in Ps:thread is the automatic proxy run method that is executed when the CPU is dispatched.

Thread construction Method (__init__):

Group=none, Target=none, Name=none, args= (), Kwargs=none, *, Daemon=none

    • Group: Thread Groups
    • Target: The method to be executed
    • Name: Thread Name
    • Args/kwargs: Parameters to pass in

Common methods:

    • Is_alive (): Returns whether the thread is running (pre-boot, before terminating).
    • GetName (): Gets the current thread name
    • SetName (): Set thread name
    • Isdaemon (): Gets whether the thread is a daemon thread.
    • Setdaemon (): Sets whether the daemon
      • If it is a background thread, during the main thread execution, the background thread is also running, and after the main thread executes, the background thread stops regardless of whether it succeeds or not.
      • If it is the foreground thread, during the main thread execution, the foreground thread is also in progress, and after the main thread executes, wait for the foreground thread to finish, the program stops
    • Start (): Start thread
    • Join ([timeout]): Blocks the current context until the thread calling this method terminates or arrives at the specified timeout value
 import   threading  import   time  def   F1 (ARG): Time.sleep ( 5 print  Span style= "color: #000000;" > (ARG) t  = Threading. Thread (target=f1,args= (123 #   true indicates that the main thread is not equal to this child thread, the default value is False, that is, the main thread waits for a child thread  T.start () #   t.join (6) #   represents the main thread to this, waiting for:  #   parameter 6, which indicates that the main thread waits at most 6 seconds  print  () 

Thread Lock

Lock

The advantage of multithreading is that you can run multiple tasks at the same time, and the data used between multiple threads can share processes and are highly efficient (but in Python, multithreading is best applied in IO-intensive programs). Because of this, there is a problem with data not synchronizing.

In order to avoid resource contention, the concept of lock was introduced. Each time a thread accesses the shared data, it must first lock, and then after processing, the processing is completed, unlocked, let other threads to process.

Because the threads are randomly dispatched, each thread may execute only N, and when multiple threads modify the same piece of data at the same time, dirty data may appear, so the lock is applied.

Example method:

    • Acquire ([timeout]) is locked, causing the thread to enter a synchronous blocking state and attempt to obtain a lock.
    • Release () releases the lock, the use of the front thread must have been locked, otherwise throws an exception.
num = tendef  F1 (args):    Global  NUM    -= 1    print(num)  for  in range:    = Threading. Thread (target=f1,args=(i,))    T.start ()# shows the result could be 10 0   In fact we want the result is 9 8 7......0   this is where the garbage data is generated.

Then we'll see that the lock will be a divine horse effect:

 num=10def   F1 (l):  global   NUM L.acquire ()  #   lock  Num-=1 Time.sleep ( 1 print   #   unlock  lock  =threading. Lock ()  for  i in  Range (10): t  =threading. Thread (Target=f1,args= #   so we can get the results we want.  

Rlock

Rlock () is a synchronous instruction that can be requested multiple times by the same thread. Rlock uses the concept of "owned threads" and "recursive hierarchy", while in a locked state, Rlock is owned by a thread. The thread that owns the Rlock can call acquire () again, releasing the lock at the same number of times that it needs to call release (). Frankly, lock can only be locked once, Rlock can lock the recursion multiple times

It can be thought that Rlock contains a lock pool and a counter with an initial value of 0, each time the acquire () and release () are successfully called, the counter is +1/-1, and 0 o'clock is unlocked.

num=10deffunc (L):GlobalNUM L.acquire ()#lockedNum-=1L.acquire ()#lockedTime.sleep (1) l.release ()#Unlock    Print(NUM) l.release ()#Unlock#lock=threading. Lock () #只能锁一次Lock=threading. Rlock ()#Lock multiple times forIinchRange (10): T=threading. Thread (target=func,args=(lock,)) T.start ()

Semaphore (semaphore)

Lock and Rlock (mutex), found at the same time can only allow a thread to change the data, the execution sequence is not serial, so-called multithreading is not God horse eggs used. Semaphore is also allowing a certain number of threads to change data. Can be understood as a mutually exclusive lock of the enhanced version, a lock can control multiple thread access, lock, you can only let a thread access, semaphore can control the number.

#Specify the release of severalnum=10deffunc (l,i):GlobalNUM L.acquire ()#lockedNum-=1Time.sleep (2)    Print(Num,i) l.release ()#UnlockLock=threading. Boundedsemaphore (5)#Lock 5 Threads forIinchRange (15): T=threading. Thread (target=func,args=(Lock,i)) T.start ()#the results displayed505 35 25) 11 405080607-4 9-5 13-5 10-5 11-5 12-5 14

The 11th chapter of the Python basics thread, process, and association

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.