多线程实现方式
Python没有真正的多线程,同一时间只能有一个线程在CPU中运行,这是由于GIL的存在导致的。
_thread模块
调用_thread模块中的start_new_thread()
函数来产生新线程。
语法
thread.start_new_thread ( function, args[, kwargs] )
- function - 线程函数。
- args - 传递给线程函数的参数,他必须是个tuple类型。
- kwargs - 可选参数。
示例
#!/usr/bin/python
# -*- coding: UTF-8 -*-
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()) ))
'''
主函数
'''
def main():
try:
for num in range(0,3):
_thread.start_new_thread( print_time, ("Thread-"+str(num), 2, ) )
except:
print("Error: unable to start thread")
if __name__ == '__main__':
main()
线程结束
线程的结束一般依靠线程函数的自然结束;也可以在线程函数中调用_thread.exit()
,他抛出SystemExit exception,达到退出线程的目的。
threading模块
使用threading模块创建线程,可以使用下面的方式,也可以直接从threading.Thread继承,然后重写__init__
方法和run
方法。
示例一
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import threading
import time
'''
当前时间
'''
def print_time(delay):
count = 0
while count < 3:
time.sleep(delay)
count += 1
print("%s: %s" % ( threading.currentThread().name, time.ctime(time.time()) ))
'''
主函数
'''
def main():
threads=[]
try:
for num in range(0,3):
threads.append(threading.Thread(target=print_time,args=(2,),name="Thread-"+str(num)))
for t in threads:
t.start()
t.join()
except:
print("Error: unable to start thread")
if __name__ == '__main__':
main()
输出结果:
Thread-0: Thu Jun 29 23:29:32 2017
Thread-0: Thu Jun 29 23:29:34 2017
Thread-0: Thu Jun 29 23:29:36 2017
Thread-1: Thu Jun 29 23:29:38 2017
Thread-1: Thu Jun 29 23:29:40 2017
Thread-1: Thu Jun 29 23:29:42 2017
Thread-2: Thu Jun 29 23:29:44 2017
Thread-2: Thu Jun 29 23:29:46 2017
Thread-2: Thu Jun 29 23:29:48 2017
join()
的作用是,在子线程完成运行之前,这个子线程的父线程将一直被阻塞,无法继续运行。所以这里会按照顺序执行线程。
示例二
'''
主函数
'''
def main():
threads=[]
try:
for num in range(0,3):
threads.append(threading.Thread(target=print_time,args=(2,),name="Thread-"+str(num)))
for t in threads:
t.start()
for t in threads:
t.join()
except:
print("Error: unable to start thread")
if __name__ == '__main__':
main()
这里的join()按照使的主线程等待所有子线程执行完成,所有线程随机执行,没有固定顺序。
示例三
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import threading,time
'''
自定义线程类
'''
class myThread(threading.Thread):
def __init__(self, threadName, delay):
threading.Thread.__init__(self)
self.threadName = threadName
self.delay = delay
def run(self):
print_time(self.threadName,self.delay)
'''
当前时间
'''
def print_time( threadName, delay):
count = 0
while count < 5:
time.sleep(delay)
count += 1
print("%s: %s" % ( threadName, time.ctime(time.time()) ))
'''
主函数
'''
def main():
threads=[]
try:
for num in range(0,3):
threads.append(myThread("Thread-"+str(num),2))
for t in threads:
t.start()
for t in threads:
t.join()
except:
print("Error: unable to start thread")
if __name__ == '__main__':
main()
网友评论