手机版
你好,游客 登录 注册
背景:
阅读新闻

Python多线程编程

[日期:2015-08-09] 来源:foofish.net  作者:foofish [字体:大 中 小]

Python2.4前有个thread模块支持多线程编程,2.4后新增了threading模块,提供更高级别和更强大的线程支持.

  • threading.activeCount():返回激活的线程对象的数量
  • threading.currentThread():返回当前cpu执行的线程对象
  • threading.enumerate(): 返回当前激活的线程对象列表

除此之外,threading提供了很多和Java中Thread类一样的方法:(注意这是都是实例方法)

  • run(): The run() method is the entry point for a thread.
  • start(): The start() method starts a thread by calling the run method.
  • join([time]): The join() waits for threads to terminate.
  • isAlive(): The isAlive() method checks whether a thread is still executing.
  • getName(): The getName() method returns the name of a thread.
  • setName(): The setName() method sets the name of a thread.

创建线程的方式有两种:

1)继承threading.Thread

a.创建一个threading.Thread的子类
b.覆盖init(self [,args])
c.重写run方法

#!/usr/bin/python 
#!coding=utf-8
import threading
import time
exitFlag = 0
class MyThread(threading.Thread):
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter

    def run(self):
        task()

    def task(self):
       '''线程要执行的任务'''
       print 'starting ' + self.name
       print 'exiting ' + self.name 

#创建线程
thread1 = MyThread(1,'Thread-1', 1)
thread2 = MyThread(2,'Thread-2', 2)

#启动线程
thread1.start()
thread2.start()

#等待线程结束
thread1.join()
thread2.join()

print 'exiting main thread'

2)任务函数作为参数传递到Thread方法中

threading.Thread(target=task, args=()).start()

下面关于Python的文章您也可能喜欢,不妨看看:

Python:在指定目录下查找满足条件的文件  http://www.linuxidc.com/Linux/2015-08/121283.htm

Python2.7.7源码分析  http://www.linuxidc.com/Linux/2015-08/121168.htm

无需操作系统直接运行 Python 代码  http://www.linuxidc.com/Linux/2015-05/117357.htm

CentOS上源码安装Python3.4  http://www.linuxidc.com/Linux/2015-01/111870.htm

《Python核心编程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm

《Python开发技术详解》.( 周伟,宗杰).[高清PDF扫描版+随书视频+代码] http://www.linuxidc.com/Linux/2013-11/92693.htm

Python脚本获取Linux系统信息 http://www.linuxidc.com/Linux/2013-08/88531.htm

在Ubuntu下用Python搭建桌面算法交易研究环境 http://www.linuxidc.com/Linux/2013-11/92534.htm

Python 语言的发展简史 http://www.linuxidc.com/Linux/2014-09/107206.htm

Python 的详细介绍:请点这里
Python 的下载地址:请点这里

本文永久更新链接地址:http://www.linuxidc.com/Linux/2015-08/121369.htm

linux
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款