1、什么是线程安全
线程是操做系统可以进行运算调度的最小单位。app
线程被包含在进程中,是进程中实际处理单位。一条线程就是一堆指令集合。函数
import threading import time def test1(threadName,delay): #为线程定义一个函数 count = 0 while count < 5: time.sleep(delay) count += 1 print("进程{0},执行时间{1}".format(threadName,time.ctime(time.time()))) try: #建立两个线程 threading._start_new_thread(test1,("thread-1",2,)) threading._start_new_thread(test1,("thread-2",4,)) except: print("Error:没法启动线程") while 1: pass
运行结果ui
2、实现多进程的两种方式操作系统
一、将要执行的方法做为参数传递给 Thread 的构造方法。——用类来包装线程对象。线程
即 t = threading.Thread(target=action, args=(i,)) 其中action 指的是线程函数。orm
二、经过 继承 的方式实现!从 Thread 继承,并重写run() 方法。对象
3、线程模块经常使用的方法。继承
一、Python3 经过两个标准库 _thread 和 threading 提供对线程的支持。队列
二、threading 模块除了包含 _thread 模块中的全部方法外,还提供的其余方法:
threading.currentThread(): 返回当前的线程变量
threading.enumerate(): 返回一个包含正在运行的线程的list。正在运行指线程启动后、结束前,不包括启动前和终止后的线程。
threading.activeCount(): 返回正在运行的线程数量,与len(threading.enumerate())有相同的结果。
三、 Thread类 方法:
3.1 run(): 用以表示线程活动的方法
3.2 start():启动线程活动
3.3 join([time]): 等待至线程停止。这阻塞调用线程直至线程的join() 方法被调用停止-正常退出或者抛出未处理的异常-或者是可选的超时发生
3.4 isAlive(): 返回线程是否活动的
3.5 getName(): 返回线程名
3.6 setName(): 设置线程名
4、线程锁
一、若是多个线程共同对某个数据修改,则可能出现不可预料的结果,为了保证数据的正确性,须要对多个线程进行同步。
二、使用 Thread 对象的 Lock 和 Rlock 能够实现简单的线程同步,这两个对象都有 acquire 方法和 release 方法,对于那些须要每次只容许一个线程操做的数据,能够将其操做放到 acquire 和 release 方法之间。
三、锁有两种状态——锁定和未锁定。
四、语法格式:经过threading.Lock()来建立锁,函数在执行的时候先要得到锁,执行完之后要释放锁。
with lock:
lock.acquire()
lock.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 ("退出主线程")
运行结果
5、线程优先排队
一、Python 的 Queue 模块中提供了同步的、线程安全的队列类,包括FIFO(先入先出)队列Queue,LIFO(后入先出)队列LifoQueue,和优先级队列 PriorityQueue。
二、Queue 模块中的经常使用方法:
2.1 Queue.qsize() 返回队列的大小
2.2 Queue.empty() 若是队列为空,返回True,反之False
2.3 Queue.full() 若是队列满了,返回True,反之False
2.4 Queue.full 与 maxsize 大小对应
2.5 Queue.get([block[, timeout]])获取队列,timeout等待时间
2.6 Queue.get_nowait() 至关Queue.get(False)
2.7 Queue.put(item) 写入队列,timeout等待时间
2.8 Queue.put_nowait(item) 至关Queue.put(item, False)
2.9 Queue.task_done() 在完成一项工做以后,Queue.task_done()函数向任务已经完成的队列发送一个信号
2.10 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 ("退出主线程")
运行结果