Python Multi-Threading usage

Source: Internet
Author: User

In the actual programming process often need to wrap tasks into multi-process or multi-threading, multi-process and multi-threading is the difference between multiple threads is memory sharing, variables and other shared, multi-process process is independent operation, so the creation of multi-threaded or multi-process depends on the different requirements.

Python because of the mechanism of global locking, so in Python in the multi-threaded run is actually only used a CPU, however, multi-threaded run is much faster than a single-threaded run.


to threading. Thread, there are roughly two ways of creating multithreading in Python.


Mode 1

Call threading in the subclass. Thread class

Import Threading. Thread

Class Metric_collector (threading. Thread):

def __init__ (self):

Threading. Thread.__init__ (self)

def run (self):

Print "Testing ..."

Time.sleep (10)

For I in range (10):

t = Metric_collector ()

T.start ()


Threading. The thread class also has the run () method, which overrides the run () method in the Metric_collector class so that the write code reads more structurally.


Mode 2

In threading. Call method in thread instance

Import Threading. Thread

Class Metric_collector (object):

def __init__ (self):

Pass

def move (self, var1, var2):

Print "testing.....%s%s"% (var1, var2)

Collector = Metric_collector ()

For I in range (10):

T=threading. Thread (target = colector.move, args = (var1, var2))

T.start ()

This method is relatively free in use.


This article from "Linux operation and Maintenance" blog, declined reprint!

Python Multi-Threading usage

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.