Python Threading Module Multithreaded source Example (i) __python

Source: Internet
Author: User

The basic idea of using the Python module threading to write multithreaded routines is to threading. The thread class derives a subclass from it, implements the business logic in the run function of the subclass, creates a thread pool of the subclass object, and executes the execution function of the subclass object.

Here is an example of multithreaded programming using the threading module in Python, in which we create a thread pool and a shared counter for 4 threads, and then let each thread preempt execution by 1 and then hibernate. This is equivalent to give a two-dimensional space, the number of threads is one-dimensional, the total number of times per thread is another dimension, from the following running results can be easily seen: the situation of the thread polling scheduling.

Note that here the print output for count needs to be included inside the mutex, otherwise the printout is incorrect.

Source Code implementation:

#!/usr/bin/env python
#encoding: utf-8

Import Threading
Import time

#入参是线程调用次数
class Test ( Threading. Thread):
    def __init__ (self, num):
        threading. Thread.__init__ (self)
        self._run_num = num

    def run (self):
        global count, mutex
        ThreadName = Threading.currentthread (). GetName ()

        for x in xrange (0, int (self._run_num)):
            mutex.acquire ()
            Print ThreadName, X, Count
            count = count + 1
            mutex.release ()
            time.sleep (1)

if __name__ = = ' __main__ ':
    global count, mutex
    threads = []
    num = 4
    count = 1
    # Create lock
    Mutex = Threading. Lock ()
    # Create thread object for
    x in xrange (0, num):
        threads.append (Test)
    # Start thread for T in
    Threads:
        T.start ()
    # Wait for child thread end for
    T in Threads:
        t.join ()

Run Effect chart:


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.