Basic use of python Multithreading

Source: Internet
Author: User

There are two ways to implement multithreading in python: one is to generate new threads through functions, and the other is to implement multithreading through object-oriented methods.

Call the start_new_thread () function in the thread module to generate a new thread.

 

#! /Usr/bin/env python # encoding: UTF-8 # author: zhxiaimport threadimport timethread_count = 0; def test (num, interval): for x in xrange ): print 'current thread is: % d, and x is: % d' % (num, x) time. sleep (interval) thread. exit_thread () if _ name __= = '_ main _': thread. start_new_thread (test, (1, 1) thread. start_new_thread (test, (2, 1) thread. start_new_thread (test, (3, 1) # To prevent the main thread from exiting before the sub-thread, you need to check the current number of sub-threads until all sub-threads have completed execution. sleep (0.001) # sleep is required. Otherwise, the number of sub-threads cannot be obtained. _ count ()> 0: time. sleep (0.5)

 

Implemented through the threading module:

#!/usr/bin/env python#encoding:utf-8#author:zhxiaimport timeimport threadingimport sysclass test(threading.Thread):        def __init__(self,num,interval):                threading.Thread.__init__(self)                self.thread_num=num                self.interval=interval        def run(self):                for x in xrange(1,9):                        print 'current thread is %d,and x is %d'%(self.thread_num,x)                        time.sleep(self.interval)if __name__=='__main__':        t1=test(1,1)        t2=test(2,1)        t3=test(3,1)        t1.start();        t2.start();        t3.start();

 

 

 

 

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.