python是一门解析性语言,python的解析器默认也是单线程的,但python3提供几个用于多线程编程的模块,_thread、threading。
python2中的thread已经废弃,为了兼容性在python3中使用_thread代替,_thread提供了原始的线程操作和简单的锁,推荐使用threading模块。
_thread模块实现多线程,使用_thread.start_new_thread()方法实现,示例如下:
import _thread
import time
def sayHi(name):
num = 0
while num < 5:
num += 1
time.sleep(1)
print("%s执行——现在时间:%sn" % (name, time.strftime(
"%Y-%m-%d %H:%M:%S", time.localtime(time.time()))))
try:
_thread.start_new_thread(sayHi, ("线程1",))
_thread.start_new_thread(sayHi, ("线程2",))
except:
print("线程启动失败")
# 保持主线程10s后退出
time.sleep(10)
# 输出结果如下:
# 线程1执行——现在时间:2018-04-12 14: 30: 38
# 线程2执行——现在时间:2018-04-12 14: 30: 38
# 线程1执行——现在时间:2018-04-12 14: 30: 39
# 线程2执行——现在时间:2018-04-12 14: 30: 39
# 线程2执行——现在时间:2018-04-12 14: 30: 40
# 线程1执行——现在时间:2018-04-12 14: 30: 40
# 线程1执行——现在时间:2018-04-12 14: 30: 41
# 线程2执行——现在时间:2018-04-12 14: 30: 41
# 线程2执行——现在时间:2018-04-12 14: 30: 42
# 线程1执行——现在时间:2018-04-12 14: 30: 42
threading模块
threading除了包含_thread的所有方法外,还提供了其他方法:
threading.currentThread():返回当前线程变量
threading.enumerate():返回正在运行的线程列表
threading.activeCount():返回当前正在运行的线程数量和len(threading.enumerate())效果相同
run():用于表示线程活动的方法
start():启动线程活动
join([time]):等待至线程结束
isAlive():线程是否是活跃的
getName():返回线程名
setName():设置线程名
threading基础使用
import time
import threading
class myThreading(threading.Thread):
def __init__(self, name):
threading.Thread.__init__(self)
self.name = name
def run(self):
time.sleep(1)
print("%s 时间:%s" %
(self.name, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))))
td1 = myThreading("threading1")
td2 = myThreading("threading2")
td1.start()
td2.start()
td1.join()
td2.join()
# 输出:
# Thread-1 时间:2018-04-14 11:19:54
# Thread-2 时间:2018-04-14 11:19:54
threading线程同步
threading使用threading.Lock()来同步线程,threading.Lock()包含锁定的方法acquire()和解锁的方法release()来同步线程,示例如下:
import time
import threading
class myThreading(threading.Thread):
def __init__(self, name):
threading.Thread.__init__(self)
self.name = name
def run(self):
# 上锁
threadLock.acquire()
time.sleep(1)
print("%s 时间:%s" %
(self.name, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))))
# 解锁
threadLock.release()
# 声明线程同步锁
threadLock = threading.Lock()
td1 = myThreading("threading1")
td2 = myThreading("threading2")
td1.start()
td2.start()
td1.join()
td2.join()



