Python Development Day9 (multithreaded multi-process)

Source: Internet
Author: User

Python Threads:
  • Introduced:
    • Threading is used to provide thread-related operations, which are the smallest unit of work in an application.
  • Use:
    • Threading method
      • . Start (): Activate thread
      • . GetName (): Gets the name of the thread
      • . SetName (): Set the name of the thread
      • . Name: Gets or sets the name of the thread
      • . Is_alive (): Determines whether a thread is active
      • . IsAlive (): Determines whether a thread is active
      • . Setdaemon () is set to either a background thread or a foreground thread (default: False), and a Boolean value that sets whether the thread is a daemon thread and must be used after the start () method is executed. If it is a background thread, during the main thread execution, the background thread is also in progress, after the main thread executes, the background thread will stop whether or not it succeeds or not; If the foreground thread is executing, the foreground thread is also in progress, and after the main thread executes, waiting for the foreground thread to finish executing, the program stops
      • . Isdaemon (): Determines whether the daemon thread
      • . Ident: Gets the identifier of the thread. The thread identifier is a non-0 integer that is valid only after the start () method is called, otherwise it only returns none.
      • . Join (): executes each thread one by one, execution continues, and the method makes multithreading meaningless
      • . Run (): The Run method for automatically executing thread objects after a thread is dispatched by the CPU
    • Direct Use unlocked:
      ImportThreadinglock= Threading. Rlock ()#define a lock of a threaddefworker (num):Print("Thread%d"%num) forIinchRange (20): T= Threading. Thread (target=worker,args= (i,), name="t.%d"%i) T.start ()#Activating Threadsexecution Result: Thread 0Thread1Thread2Thread6Thread4Thread3Thread5Thread8Thread10Thread9Thread7Thread13Thread12Thread11Thread16Thread14Thread15Thread19Thread18Thread17
      View Code
    • Use Lock:
      ImportThreadinglock= Threading. Rlock ()#define a lock of a threaddefworker (num): Lock.acquire ()#Locking    Print("Thread%d"%num) lock.release ()#Unlock forIinchRange (20): T= Threading. Thread (target=worker,args= (i,), name="t.%d"%i) T.start ()#Activating Threadsexecution Result: Thread 0Thread1Thread2Thread3Thread4Thread5Thread6Thread7Thread8Thread9Thread10Thread11Thread12Thread13Thread14Thread15Thread16Thread17Thread18Thread19
      View Code
    • There are two types of thread locks for Rlock, one for lock
      • Lock parsing:
         lock = Threading. Lock () #   define a thread lock  lock.acquire () #   lock  print  (123) Lock.acquire ()  #   lock Creates a deadlock  print  (234) Lock.release ()  #  Span style= "color: #008000;" > unlock  print  (345 Span style= "color: #008000;" >#   unlock  #   deadlock, lock yourself up again and apply lock yourself to wait for yourself to release the lock.   execution result:  123 wait for  ~~~~~~~~~~ 
        view code
      • Rlock parsing:
        Lock = Threading. Rlock ()# defines a thread lock lock.acquire ()# locking print(123) Lock.acquire () # Locking Print (234) lock.release () # Unlock Print (345) lock.release () # Unlock        # He will not have a deadlock, but pay attention to how many locks it takes to release. execution Result:123234345
        View Code

Use event for communication between threads

    • Introduced:
      • Event is one of the most mechanisms of inter-thread communication: One thread sends an event signal, while the other threads wait for the signal. Used for the main thread to control the execution of other threads. Events manages a flag that can be set to true using Set () or reset to false,wait () using clear () to block, before flag is true. Flag defaults to False.
    • Use:
      • Event.wait ([timeout]): Blocks the thread until the event object's internal identity bit is set to true or timed out (if parameter timeout is provided).
      • Event.set (): Set the identity bit to ture
      • Event.clear (): Sets the identity companion to False.
      • Event.isset (): Determines whether the identity bit is ture.
      • code example:
        ImportThreadingdefDo (event):Print('Start') event.wait ()Print('Execute') Event_obj=Threading. Event () forIinchRange (10): T= Threading. Thread (Target=do, args=(Event_obj,)) T.start () event_obj.clear () InP= Input ('Input:')ifINP = ='true': Event_obj.set () execution result: Startstartstartstartstartinput:trueexecuteexecuteexecuteexecuteexecute
        View CodeWhen the thread executes, if flag is false, the thread blocks and the thread does not block when flag is true. It provides both local and remote concurrency.

Queue module:
  • Introduced:
    • The queue is the pair of queues, it is thread-safe (for example, we go to KFC for dinner.) The kitchen is for us to cook the place, the front desk is responsible for the kitchen cooked meal sells the customer, the customer goes to the front desk to collect the good meal. The front desk here is the equivalent of our queue.

      This model is also called producer-consumer models. )

  • Use:
    • Method:
      ImportQueueq= Queue. Queue (maxsize=0)#constructs an advanced presentation queue, maxsize specifies the queue length, which is 0 o'clock, which indicates that the queue length is unlimited. Q.join ()#when the queue is Kong, perform other operationsQ.qsize ()#returns the size of the queue (unreliable)Q.empty ()#returns True if the queue is empty, otherwise false (unreliable)Q.full ()#returns True when the queue is full, otherwise false (unreliable)Q.put (item, block=true, Timeout=none)#put item in the queue tail, item must exist, can parameter block default is True, indicating that when the queue is full, waiting for the queue to give the available location,is non-blocking when false, and a queue is raised if it is full at this time. Full exception. Optional parameter timeout, which indicates the time at which the setting is blocked, and, after that, if the queue cannot give the location to which it was placed, it raises the queue. Full exception Q.get (Block=true, Timeout=none)#Remove and return a value for the header of the queue, optional parameter block defaults to True, indicating that when the value is fetched, if the queue is empty, it is blocked, false, not blocked,if the queue is empty at this point, queue is raised. Empty exception. Optional parameter timeout, which indicates that the setting is blocked, and then, if the queue is empty, throws an empty exception. Q.put_nowait (item)#equivalent to put (Item,block=false)Q.get_nowait ()#equivalent to get (item,block=false)

    • Use:
      ImportThreading,queuemessage= Queue. Queue (10)defproducer (i):Print('>>>>>', i) message.put (i)defConsumer (i): Msg=Message.get ()Print('Date', msg) forIinchRange (12): T= Threading. Thread (Target=producer, args=(i,)) T.start () forIinchRange (10): T= Threading. Thread (Target=consumer, args=(i,)) T.start () execution Result:>>>>>0>>>>> 1>>>>> 2>>>>> 3>>>>> 4>>>>> 5> >>>> 6>>>>> 7>>>>> 8>>>>> 9>>>>> 10>> >>> 11Date 0date1Date2Date3Date4Date5Date6Date7Date8Date9
      View Code

Python Development Day9 (multithreaded multi-process)

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.