How Python multi-thread multi-threaded print avoids the clutter of print results

Source: Internet
Author: User

Multithread How to Write

This is my first time to write multithread, so just follow the example, here is the example I used to learn

From "Automate the boring stuff with Python" 15.6

Importthreading, TimePrint "Start of the program" def takeanap():Time.sleep (5)Print "Wake up!"Thread1 = Threading. Thread (target = Takeanap) Thread1.start ()Print "End of the program"

OK, the result of this applet will be end of ... This sentence first print out, and then wake up again appear, in fact, "automate the boring ..." This book on multithreading in the two examples, this is the first, the second is to tell how to pass the parameters to multithreading, but after reading it found that the program of today is not very helpful, Because today's program is a big part of the difficulty is print, then the following is the source of the requirements of the program and the first attempt to fail.

Take a multithreaded print program as an example
  • Demand:
    Using multi-threading, on three different routers, show arp and output

  • Problem:
    Obviously, the output will messed up because each thread has a fast and slow

  • The initial thought of the method

    • You can save two results to an external file, then have a structured read, then a structured print. I think this is feasible, but this obviously practice is not multithread characteristics, because multithread is related to memory, storage to disk re-read, it feels a bit contrary to the advantages of full use of multithreading, and this is a small program, is purely display problems.

    • Threading. Lock ()

First of all, this failure, because print is very special, its own printing speed will still affect, this is not a thread is executed after the problem, but a thread after the execution of its output print is not fast enough and how to solve the problem, so lock () can not help

The relevant code for Lock ():

I created the subclass of my thread according to the example in this link.

    • This mythread will take the device class, that is, a router as the object, Printarp

    • I added acquire () to lock and release () to unlock the print before and after

 class myThread(threading. Thread):   def __init__(self, device):Threading. Thread.__init__ (self) self.device = device def run(self):ThreadLock1 = Threading. Lock () Threadlock1.acquire () Printarp (Self.device) threadlock1.release ()

Then call the subclass, turn on each subclass instantiation of the thread, put each thread into an array, the array is called. Join ()

thread1 = myThread(rtr1)thread2 = myThread(rtr2)thread3 = myThread(srx)thread1.start()thread2.start()thread3.start()threads = []threads.append(thread1)threads.append(thread2)threads.append(thread3)forin threads:  t.join()print"All done"

However, there are no eggs, even if you use them. Join let them go back to the main thread, and say join () for a moment.

  • The Final Solution
    • Sys.stdout.write (a_string)

Yes, this is the goods, I see from this link, the last answer is

The exact words are

' The issue is so Python uses seperate opcodes for the NEWLINE printing and the printing of the object itself. The easiest solution is probably to just use a explicit sys.stdout.write with an explicit newline. '

And then here's a comment that's sys.stdout.write usage.

' From my recent experience, this is absolutely true. I ' m not exactly sure what it happens, but the printstatement (even when STDOUT was properly serialized and flushed) would out Put erratic newlines. You must usesys.stdout.write (s + ' \ n ') to avoid this. ‘

Of course, there is a comment below that the man above said still need lock, but anyway, this sys.stdout.write (a_string) solved my problem

  • The final code is this.
    • Do not use your own defined subclass, still use the threading. Thread () to create a new thread
  thread1 = threading.Thread(target=printARP, args=[rtr1])  thread2 = threading.Thread(target=printARP, args=[rtr2])  thread3 = threading.Thread(target=printARP, args=[srx])

And the rest is the same.

    • The only place that needs to be changed

Printarp This function module, change to the following, change print to Sys.stdout.write () remember to introduce SYS

 def printarp(device):  "Print the ARP table on this device"conn = Connecthandler (**device)#sys. Stdout.flush ()ARP = Conn.send_command ("Show Arp") Time.sleep (1) OUTP = ("ARP table on%s:"% Get_name_of_obj (device,"Each_device")+"\ n")# Use Find_prompt () to determin the output of threads is not messed upOUTP + = (conn.find_prompt () +"\ n") OUTP + = (arp+"\ n") OUTP + ="*********************\n"Sys.stdout.write (OUTP)

The complete code is here

Join of a thread

Almost forgot to say that the answer to the Lord is particularly good, the picture is absolutely perfect.

?

How Python multi-thread multi-threaded print avoids the clutter of print results

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.