Threading Multithreading in Python

Source: Internet
Author: User

There are two modules thread and threading that handle multithreading in Python. Thread provides a multi-threaded support of the module, with the low-level original hair that is to handle and control the thread, the use of more complex, and threading based on thread wrapper, the threading operation of the object.

The most basic multi-threading

Let's look at one of the most basic multithreaded examples

ImportThreadingImport TimeclassTest (threading. Thread):def __init__(Self,name,delay): Threading. Thread.__init__(self) self.name=name Self.delay=DelaydefRun (self):Print "%s is running"%Self.name forXinchRange (Self.delay): Time.sleep (1)           Print "%s is saying hello%d"%(self.name,x)defMain (): T1= Test ('Thread 1', 3) T2= Test ('Thread 2', 2) T1.start () T2.start ()if __name__=='__main__': Main ()Print "End of Main"

The output results are as follows:

Thread 1 is running
End of Mainthread 2 is running

Thread 1 is saying hello 0
Thread 2 is saying hello 0
Thread 1 is saying hello 1
Thread 2 is saying hello 1
Thread 1 is saying hello 2

It can be seen that Thread1 and Thread2 basically take turns, which is the benefit of multithreading, otherwise it would take twice times to execute 2 programs sequentially.

Start is the encapsulation of the thread's Run (), which executes the run () function when the start () is called.

What if we change the paragraph in the code to the following?

def Main ():     = Test ('thread 1', 3)    = Test ('thread 2', 2  )    T1.start ()    print"wait for thread1 end"     T1.join ()    T2.start ( )

The output is:

Wait for Thread1 Endthread 1 is running

Thread 1 is saying hello 0
Thread 1 is saying hello 1
Thread 1 is saying hello 2
End of Mainthread 2 is running

Thread 2 is saying hello 0
Thread 2 is saying hello 1

As can be seen from the above, after calling T1.join (), T2 will wait until T1 execution is complete before execution begins.

Multithreaded Programming with queue
using thread queues

As mentioned earlier, when multiple threads need to share data or resources, the use of threads can become complex. The threading module provides a number of synchronization primitives, including semaphores, condition variables, events, and locks. When these options exist, the best practice is to focus instead on using queues. By comparison, queues are easier to handle and can make threading programming more secure because they effectively deliver all access to resources for a single thread and support clearer, more readable design patterns.

ImportThreadingImport TimeImportQueueImportUrllib2ImportOSclassTest (threading. Thread):def __init__(self,queue): Threading. Thread.__init__(self) self.queue=QueuedefRun (self): while1: URL=Self.queue.get ()Printself.name+"begin Download"+url+"..."self.download (URL) self.queue.task_done ()Printself.name+"Download Completed"    defDownload (self,url): Urlhandle=urllib2.urlopen (URL) with open (Os.path.basename (URL)+". html","WB") as FP: while1: Contents=urlhandle.read (1024)                if  notContents: Break                Else: Fp.write (contents)defMain (): Ulrs= ["http://wiki.python.org/moin/Webprograming",    "https://www.baidu.com",    "http://wiki.python.org/moin/Documendation"] Q= Queue.queue (5)     foreachinchUlrs:q.put (each) forIinchRange (5): T=Test (q) T.setdaemon (True) T.start () Q.join ()if __name__=='__main__': Main ()

join()
remains blocked until all items in the queue have been processed. When you add a project to the queue, the total number of outstanding tasks increases. When a consumer thread calls Task_done () to indicate that the project has been retrieved and all the work has been done, the total number of unfinished tasks is reduced. When the total number of unfinished tasks is reduced to 0 o'clock, the join() blocking state is ended.

Each thread runs from the queue get a URL, when the queue length is reduced by 1, and then the completion of the time to send a notification. All execution is completed until the queue is empty.

When debugging, it is found that the same results can be obtained even if you do not Task_done (). But the main thread will always be blocked from continuing, so Task_done's task is to tell the main thread that the current task is complete and to decrement the number of outstanding tasks so that the main thread knows when all the tasks are done, and then continues execution.

Threading Multithreading in Python

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.