一、 线程有5种状态
1、新建 new出一个线程对象。
2、可运行,调用了start方法,表示已经准备好运行,但是还没轮到cpu执行它。3、运行 :获得cpu咨询,进入执行状态。4、挂起阻塞中断睡眠: 在执行阶段,遇到lock/事件等待/io/sleep等,进入这个状态,会调用join方法等待其他线程。这里需要注意的事情是:死锁。5、停止(销毁): 线程运行借结束,释放线程占有的资源。二、线程切换
线程在未执行完毕之前,可以切换,有两种情况。一是等待其他线程,也就是被中断。二是cpu时间片结束,执行其他线程。
三、Threading模块
Python中提供了_thread和Threading模块实现了线程各种功能。_thread 提供了低级别的、原始的线程以及一个简单的锁,类似于c语言函数式调用接口,threading是对_thread接口的包装,类似C++对c语言的wrapper,同时也提供了更多的方法。
1、产生一个线程,函数的方式如下:
_thread.start_new_thread ( function, args[, kwargs] )
线程模块的方式如下:
#!/usr/bin/python3
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):
print ("开始线程:" + self.name)
print_time(self.name, self.counter, 5)
print ("退出线程:" + self.name)
def print_time(threadName, delay, counter):
while counter:
if exitFlag:
threadName.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()
thread1.join()
thread2.join()
print ("退出主线程")
2、threading模块功能
1)threading.currentThread(): 返回当前的线程变量。2)threading.enumerate(): 返回一个包含正在运行的线程的list。正在运行指线程启动后、结束前,不包括启动前和终止后的线程。3)threading.activeCount(): 返回正在运行的线程数量,与len(threading.enumerate())有相同的结果。run(): 用以表示线程活动的方法。
start():启动线程活动。join([time]): 等待至线程中止。这阻塞调用线程直至线程的join() 方法被调用中止-正常退出或者抛出未处理的异常-或者是可选的超时发生。isAlive(): 返回线程是否活动的。getName(): 返回线程名。setName(): 设置线程名。注意:调用run启动线程,join方法将会无效。
四、线程同步
1、lock锁
线程之间共享进程内的数据资源,通过共享数据,可以做到通信。同时如果多个线程要对同一个数据(这个数据成为临界资源)做修改,麻烦很大。因此有了lock,从而实现线程同步。threading模块里提供了lock/rlock两个对象,每个对象都有acquire/release两个方法,表示对临界资源的控制权。举例如下:import threading
import time
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):
print ("开启线程:" + self.name)
# 获取锁,用于线程同步
threadLock.acquire()
print_time(self.name, self.counter, 3)
# 释放锁,开启下一个线程
threadLock.release()
def print_time(threadName, delay, counter):
while counter:
time.sleep(delay)
print ("%s: %s" % (threadName, time.ctime(time.time())))
counter -= 1
threadLock = threading.Lock()
threads = []
# 创建新线程
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
# 开启新线程
thread1.start()
thread2.start()
# 添加线程到线程列表
threads.append(thread1)
threads.append(thread2)
# 等待所有线程完成
for t in threads:
t.join()
print ("退出主线程")
#输出结果
开启线程:Thread-1
开启线程:Thread-2
Thread-1: Wed Apr 6 11:52:57 2016
Thread-1: Wed Apr 6 11:52:58 2016
Thread-1: Wed Apr 6 11:52:59 2016
Thread-2: Wed Apr 6 11:53:01 2016
Thread-2: Wed Apr 6 11:53:03 2016
Thread-2: Wed Apr 6 11:53:05 2016
退出主线程
2、queue
Queue模块提供了同步的、线程安全的列队类,包括FIFO,这些队列都实现了锁原语,能够在多线程中直接使用。Queue 模块中的常用方法:Queue.qsize() 返回队列的大小Queue.empty() 如果队列为空,返回True,反之FalseQueue.full() 如果队列满了,返回True,反之FalseQueue.full 与 maxsize 大小对应Queue.get([block[, timeout]])获取队列,timeout等待时间Queue.get_nowait() 相当Queue.get(False)Queue.put(item) 写入队列,timeout等待时间Queue.put_nowait(item) 相当Queue.put(item, False)Queue.task_done() 在完成一项工作之后,Queue.task_done()函数向任务已经完成的队列发送一个信号Queue.join() 实际上意味着等到队列为空,再执行别的操作import queue
import threading
import time
exitFlag = 0
class myThread (threading.Thread):
def __init__(self, threadID, name, q):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.q = q
def run(self):
print ("开启线程:" + self.name)
process_data(self.name, self.q)
print ("退出线程:" + self.name)
def process_data(threadName, q):
while not exitFlag:
queueLock.acquire()
if not workQueue.empty():
data = q.get()
queueLock.release()
print ("%s processing %s" % (threadName, data))
else:
queueLock.release()
time.sleep(1)
threadList = ["Thread-1", "Thread-2", "Thread-3"]
nameList = ["One", "Two", "Three", "Four", "Five"]
queueLock = threading.Lock()
workQueue = queue.Queue(10)
threads = []
threadID = 1
# 创建新线程
for tName in threadList:
thread = myThread(threadID, tName, workQueue)
thread.start()
threads.append(thread)
threadID += 1
# 填充队列
queueLock.acquire()
for word in nameList:
workQueue.put(word)
queueLock.release()
# 等待队列清空
while not workQueue.empty():
pass
# 通知线程是时候退出
exitFlag = 1
# 等待所有线程完成
for t in threads:
t.join()
print ("退出主线程")
精彩评论