Python基础--多线程
2016-03-27 10:03
591 查看
多线程在程序开发过程中特别重要,我们往往把一些耗时的操作在子线程中执行,这就是所谓的多线程了。
在C++11中,写了一些关于多线程的博客。
Python也不例外,当然也要有多线程了。
python提供了两个模块来实现多线程thread 和threading ,thread 有一些缺点,在threading 得到了弥补
thread
通过start_new_thread函数来开启新的线程,位于thread模块中:
原型:
直接上代码:
threading
使用threading线程模块创建线程:
自定义一个类继承自threading.Thread
Thread.getName()
Thread.setName()
Thread.name
用于获取和设置线程的名称。
Thread.ident
获取线程的标识符。线程标识符是一个非零整数,只有在调用了start()方法之后该属性才有效,否则它只返回None。
Thread.is_alive()
Thread.isAlive()
判断线程是否是激活的(alive)。从调用start()方法启动线程,到run()方法执行完毕或遇到未处理异常而中断 这段时间内,线程是激活的。
Thread.join([timeout])
调用Thread.join将会使主调线程堵塞,直到被调用线程运行结束或超时。参数timeout是一个数值类型,表示超时时间,如果未提供该参数,那么主调线程将一直堵塞到被调线程结束
在C++11中,写了一些关于多线程的博客。
Python也不例外,当然也要有多线程了。
python提供了两个模块来实现多线程thread 和threading ,thread 有一些缺点,在threading 得到了弥补
thread
通过start_new_thread函数来开启新的线程,位于thread模块中:
原型:
thread.start_new_thread ( function, args[, kwargs] )
直接上代码:
import thread import time # 为线程定义一个函数 def print_time( threadName, delay): count = 0 while count < 5: time.sleep(delay) count += 1 print "%s: %s" % ( threadName, time.ctime(time.time()) ) # 创建两个线程 try: thread.start_new_thread( print_time, ("Thread-1", 2, ) ) thread.start_new_thread( print_time, ("Thread-2", 4, ) ) except: print "Error: unable to start thread" while 1: pass
threading
使用threading线程模块创建线程:
自定义一个类继承自threading.Thread
import threading import time exitFlag = 0 class myThread (threading.Thread): #继承父类threading.Thread def __init__(self, threadID, name, counter): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.counter = counter def run(self): #把要执行的代码写到run函数里面 线程在创建后会直接运行run函数 print "Starting " + self.name print_time(self.name, self.counter, 5) print "Exiting " + self.name def print_time(threadName, delay, counter): while counter: if exitFlag: thread.exit() time.sleep(delay) print "%s: %s" % (threadName, time.ctime(time.time())) counter -= 1 # 创建新线程 thread1 = myThread(1, "Thread-1", 1) thread2 = myThread(2, "Thread-2", 2) # 开启线程 thread1.start() thread2.start() print "Exiting Main Thread"
Thread.getName()
Thread.setName()
Thread.name
用于获取和设置线程的名称。
Thread.ident
获取线程的标识符。线程标识符是一个非零整数,只有在调用了start()方法之后该属性才有效,否则它只返回None。
Thread.is_alive()
Thread.isAlive()
判断线程是否是激活的(alive)。从调用start()方法启动线程,到run()方法执行完毕或遇到未处理异常而中断 这段时间内,线程是激活的。
Thread.join([timeout])
调用Thread.join将会使主调线程堵塞,直到被调用线程运行结束或超时。参数timeout是一个数值类型,表示超时时间,如果未提供该参数,那么主调线程将一直堵塞到被调线程结束
相关文章推荐
- python得到所有在leetcode上Accepted的代码(一)
- python简单浮点数匹配
- Python使用sqlite3操作数据库
- NumPy学习笔记2
- NumPy学习笔记1
- Python的安装及升级
- 利用python pil 实现给图片上添加文字
- Python中的url编码问题
- Python Django框架搭建
- Python学习之路
- python入门-简单数据类型
- 浅析python中的变量
- python之print
- Python:用generator构造树和遍历(探究yield和yield from)
- 每天一篇python:函数篇
- Python 程序设计语言 笔记(二)
- Mac anaconda python mysql
- Python2.6和Python3.0中八进制数字表示区别
- Python标准库 - time module
- Python机器学习实战(二)--决策树