1 简单用法
代码语言:javascript复制import threading
i=0
def foo():
for i in range(10):
i =1
print i
t1 = threading.Thread(target=foo)
t2 = threading.Thread(target=foo)
t1.start()
t2.start()
2 锁 #创建锁 mutex = threading.Lock() #锁定 mutex.acquire([timeout]) #释放 mutex.release() 3 event同步锁与线程类 event可以做为一个阻塞开关,阻塞时,如果另一边执行.set,就会释放阻塞。.clear函数可以恢复阻塞状态。
代码语言:javascript复制import threading
import time
import random
#使用event同步,依次打印线程名,若不加event锁,则为乱序
#两个线程依次循环:阻塞--> 等待对方释放自己 -->执行打印 -->恢复自己的阻塞 --> 释放对方
class Mythread1(threading.Thread):
def __init__(self,myevent,otherevent):
threading.Thread.__init__(self)
self.threadEvent = myevent
self.otherEvent = otherevent
self.i=0
def run(self):
while(self.i<10):
self.threadEvent.wait() #首先阻塞,等待另一边的线程释放这个锁
time.sleep(random.randint(1,100)/70)
self.i =1
print self.name,
self.threadEvent.clear() #完成任务后,恢复event锁的可阻塞状态,让下个循环仍然会阻塞,等待释放
self.otherEvent.set() #解锁另一个线程的阻塞,两个线程依次等待对方,依次执行,就能打印顺序的线程名
class Mythread2(threading.Thread):
def __init__(self,myevent,otherevent):
threading.Thread.__init__(self)
self.threadEvent = myevent
self.otherEvent = otherevent
self.i=0
def run(self):
while(self.i<10):
self.threadEvent.wait()
time.sleep(random.randint(1,100)/70)
self.i =1
print self.name,
self.threadEvent.clear()
self.otherEvent.set()
sinal1 = threading.Event()
sinal2 = threading.Event()
t1 = Mythread1(sinal1,sinal2)
t2 = Mythread2(sinal2,sinal1)
t1.start()
t2.start()
sinal1.set()
t1.join()
t2.join()
4 线程池 了解原理后,就能自己实现一个
代码语言:javascript复制import Queue
import threading
class ThreadPool(object):
def __init__(self, work_num=1000,thread_num=2):
self.work_queue = Queue.Queue(maxsize = work_num)
self.threads = []
self.__init_thread_pool(thread_num)
def __init_thread_pool(self,thread_num):
for i in range(thread_num):
self.threads.append(Work(self.work_queue))
def Add(self, func, *args):
self.work_queue.put((func, list(args)))
def Wait(self):
for item in self.threads:
if item.isAlive():item.join()
def Dispose(self):
for item in self.threads:
item.dispose=True
class Work(threading.Thread):
def __init__(self, work_queue):
threading.Thread.__init__(self)
self.work_queue = work_queue
self.dispose=False
self.start()
def run(self):
while True:
try:
tempfunc, args = self.work_queue.get(timeout=5)
tempfunc(*args)
except:
if self.dispose==True:
break
pass
调用
import threadpool
import threading
import time
def do_job(val1,val2):
time.sleep(0.1)
print val1,val2
pool = threadpool.ThreadPool() #new 一个线程池
for i in range(10):
pool.Add(do_job,"hello",i) #添加十个任务到池中,它们一定会执行
time.sleep(1)
for i in range(10):
pool.Add(do_job,"hello",i) #再添加十个任务到池中,它们一定会执行
t1 = threading.Thread(target=pool.Dispose()) #另起一个线程,发送dispose命令到线程池,在任务完成后线程池销毁
t1.start()
pool.Wait() #这个函数很有意思,等待线程池中的任务全部完成,一般系统级的线程池不会有这个函数
官方其实也提供了线程池,更简单稳定:
代码语言:javascript复制from multiprocessing.dummy import Pool as ThreadPool
import time
def loop():
i = 0
while True:
i = 1
# print("loop run", i)
time.sleep(1)
def print_name():
while True:
strs = input("input:")
print("print_name", strs)
p = ThreadPool(4)
p.apply_async(loop)
p.apply_async(print_name)
p.close()
p.join()