1 # -*- coding:utf-8 -*- 2 import threading 3 from time import sleep 4 lock = threading.Lock() 5 tmp_list = [] 6 class MyThread(threading.Thread): 7 """ 8 此线程用于向公共队列中追加元素 9 """ 10 def __init__(self): 11 threading.Thread.__init__(self) 12 #: 向公共队列追加元素 13 def run(self): 14 i = 1 15 sleep(1) 16 while True: 17 tmp_list.append(i) 18 print "i = %d, tmp_list = %s" %(i, tmp_list) 19 i += 1 20 sleep(1) 21 22 def main(): 23 sub_thread = MyThread() 24 sub_thread.start() 25 sleep(3) 26 while True: 27 length = len(tmp_list) 28 try: 29 if length > 0: 30 print "after pop, list is : %s" %tmp_list 31 for j in range(length): 32 tmp_list.pop() 33 34 except IndexError: 35 print "list empty" 36 continue 37 38 if __name__ == "__main__": 39 main()
以上代码结果显示,涉及多线程工操作同一队列时,一插一查/删,即两者不会相互影响,不需要对队列加锁,
如果涉及其一线程操作会影响另一者操作,则要加锁。
涉及到容器类的加锁,应避免全局加锁,尽量局部加锁,并及时释放锁。