• 多线程共享一个队列


     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()

    以上代码结果显示,涉及多线程工操作同一队列时,一插一查/删,即两者不会相互影响,不需要对队列加锁,

    如果涉及其一线程操作会影响另一者操作,则要加锁。

    涉及到容器类的加锁,应避免全局加锁,尽量局部加锁,并及时释放锁。

  • 相关阅读:
    HDU 5313 bitset优化背包
    bzoj 2595 斯坦纳树
    COJ 1287 求匹配串在模式串中出现的次数
    HDU 5381 The sum of gcd
    POJ 1739
    HDU 3377 插头dp
    HDU 1693 二进制表示的简单插头dp
    HDU 5353
    URAL 1519 基础插头DP
    UVA 10294 等价类计数
  • 原文地址:https://www.cnblogs.com/johnchain/p/3431028.html
Copyright © 2020-2023  润新知