zoukankan      html  css  js  c++  java
  • 多线程共享一个队列

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

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

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

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

  • 相关阅读:
    004.Jquery库的用法
    update 死锁问题
    Nginx负载均衡模式
    微信公众号开启服务器配置 JAVA
    mybatis plus + AOP 多数据源自动切换
    mybatis plus 快速上手
    mybits 笔记
    java 异步
    node 垃圾回收机制
    常用正则
  • 原文地址:https://www.cnblogs.com/johnchain/p/3431028.html
Copyright © 2011-2022 走看看