http://www.cnblogs.com/yuanchenqi/articles/6755717.html
import threading from time import ctime,sleep import time def Music(name): print ("Begin listening to {name}. {time}".format(name=name,time=ctime())) sleep(3) print(threading.activeCount()) print(threading.enumerate()) print("end listening {time}".format(time=ctime())) def Blog(title): print ("Begin recording the {title}. {time}".format(title=title,time=ctime())) sleep(5) print('end recording {time}'.format(time=ctime())) threads = [] t1 = threading.Thread(target=Music,args=('FILL ME',),name="sub_thread") t2 = threading.Thread(target=Blog,args=('',)) threads.append(t1) threads.append(t2) if __name__ == '__main__': t1.setDaemon(True) # daemon:监听,主进程一直等,只等t2 for t in threads: t.start() print ("all over %s" %ctime())
GIL影响是同一时刻一个进程中只能有一个线程在执行,对于cpu密集型的没有意义,但是对于IO密集型的有意义
同步锁
import time import threading def subNum(): global num #在每个线程中都获取这个全局变量 # num-=1 print("ok") lock.acquire()#加锁开始 temp=num time.sleep(0.1) num =temp-1 # 对此公共变量进行-1操作 lock.release()#加锁结束,只对中间圈的起作用,而join是对整个都是串行的,ok不会全部打印出来 num = 100 #设定一个共享变量 thread_list = [] lock=threading.Lock()#不允许其他线程来切,必须执行完才能切,是为是保护数据, for i in range(100): t = threading.Thread(target=subNum) t.start() thread_list.append(t) # t.join() for t in thread_list: #等待所有线程执行完毕 t.join() print('Result: ', num)
递归锁
import threading import time #递归锁,rlock,只要涉及到公共数据,数据安全的时候,是唯一的安全机制,他内部有个计数器1,2 #同步锁不能acquire多次,建议多用递归锁 # mutexA = threading.Lock() # mutexB = threading.Lock() Rlock=threading.RLock() class MyThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): self.fun1() self.fun2() def fun1(self): Rlock.acquire() # 如果锁被占用,则阻塞在这里,等待锁的释放 print ("I am %s , get res: %s---%s" %(self.name, "ResA",time.time())) Rlock.acquire() # count=2 print ("I am %s , get res: %s---%s" %(self.name, "ResB",time.time())) Rlock.release() #count-1 Rlock.release() #count-1 =0 def fun2(self): Rlock.acquire() # count=1 print ("I am %s , get res: %s---%s" %(self.name, "ResB",time.time())) time.sleep(0.2) Rlock.acquire() # count=2 print ("I am %s , get res: %s---%s" %(self.name, "ResA",time.time())) Rlock.release() Rlock.release() # count=0 if __name__ == "__main__": print("start---------------------------%s"%time.time()) for i in range(0, 10): my_thread = MyThread() my_thread.start()
event对像
#EVent就是线程间通信用的 import threading import time import logging logging.basicConfig(level=logging.DEBUG, format='(%(threadName)-10s) %(message)s',) def worker(event): logging.debug('Waiting for redis ready...') while not event.isSet(): logging.debug("wait.......") event.wait(3) # if flag=False阻塞,等待flag=true继续执行 logging.debug('redis ready, and connect to redis server and do some work [%s]', time.ctime()) time.sleep(1) def main(): readis_ready = threading.Event() # flag=False t1 = threading.Thread(target=worker, args=(readis_ready,), name='t1') t1.start() t2 = threading.Thread(target=worker, args=(readis_ready,), name='t2') t2.start() logging.debug('first of all, check redis server, make sure it is OK, and then trigger the redis ready event') time.sleep(6) # simulate the check progress readis_ready.set() # flag=Ture if __name__=="__main__": main()
进程
# from multiprocessing import Process # # # import time # # # def f(name): # # print('hello', name,time.ctime()) # time.sleep(1) # # if __name__ == '__main__': # p_list=[] # # for i in range(3): # p = Process(target=f, args=('alvin:%s'%i,)) # p_list.append(p) # p.start() # # # # for i in p_list: # # p.join() # # print('end')
from multiprocessing import Process import os import time def info(name): print("name:",name) print('parent process:', os.getppid()) print('process id:', os.getpid()) print("------------------") def foo(name): info(name) time.sleep(50) if __name__ == '__main__': info('main process line') p1 = Process(target=info, args=('alvin',)) p2 = Process(target=foo, args=('egon',)) p1.start() p2.start() p1.join() p2.join() print("ending") time.sleep(100)
协程
主要应用:还是在IO操作上,当你遇到IO操作,
优点:1 就切换单线程,不存在切换,2,不存在锁的概念
greenlt框架
gevent模块实现协程