码迷,mamicode.com
首页 > 编程语言 > 详细

python 多线程的使用

时间:2016-05-25 22:39:03      阅读:228      评论:0      收藏:0      [点我收藏+]

标签:python 多线程

在实际编程过程中经常需要把任务包装成多进程或者多线程,多进程和多线程的区别在于多线程是内存共享、变量等共享的,多进程的进程间是独立运行的,所以创建多线程还是多进程取决于不同的需求。

python中因为有全局锁的机制,所以在python中多线程跑的时候其实只是在用一个CPU,尽管如此,多线程跑还是比单线程跑要快很多。


以threading.Thread来说,在python中创建多线程大致有两种方式。


方式1

在子类中调用threading.Thread类

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.Thread类中也有run()方法,在Metric_Collector类中重写了run()方法,这样写代码读起来比较结构化。


方式2

在threading.Thread实例中调用方法

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()

这种方法在使用中比较自由。


本文出自 “Linux运维” 博客,谢绝转载!

python 多线程的使用

标签:python 多线程

原文地址:http://haohaozhang.blog.51cto.com/9176600/1783174

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!