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