zoukankan      html  css  js  c++  java
  • python 类变量 在多线程下的共享与释放问题

    最近被多线程给坑了下,没意识到类变量在多线程下是共享的,还有一个就是没意识到 内存释放问题,导致越累越大

    1.python 类变量 在多线程情况 下的 是共享的

    2.python 类变量 在多线程情况 下的 释放是不完全的

    3.python 类变量 在多线程情况 下没释放的那部分 内存 是可以重复利用的

     1 import threading
     2 import time
     3 
     4 class Test:
     5 
     6     cache = {}
     7     
     8     @classmethod
     9     def get_value(self, key):
    10         value = Test.cache.get(key, [])
    11         return len(value)
    12 
    13     @classmethod
    14     def store_value(self, key, value):
    15         if not Test.cache.has_key(key):
    16             Test.cache[key] = range(value)
    17         else:
    18             Test.cache[key].extend(range(value)) 
    19         return len(Test.cache[key])
    20 
    21     @classmethod
    22     def release_value(self, key):
    23         if Test.cache.has_key(key):
    24             Test.cache.pop(key)
    25         return True
    26 
    27     @classmethod
    28     def print_cache(self):
    29         print 'print_cache:'
    30         for key in Test.cache:
    31             print 'key: %d, value:%d' % (key, len(Test.cache[key]))
    32 
    33 def worker(number, value):
    34     key = number % 5
    35     print 'threading: %d, store_value: %d' % (number, Test.store_value(key, value))
    36     time.sleep(10)
    37     print 'threading: %d, release_value: %s' % (number, Test.release_value(key))
    38 
    39 if __name__ == '__main__':
    40     thread_num = 10
    41     
    42     thread_pool = []
    43     for i in range(thread_num):
    44         th = threading.Thread(target=worker,args=[i, 1000000])
    45         thread_pool.append(th)
    46         thread_pool[i].start()
    47 
    48     for thread in thread_pool:
    49         threading.Thread.join(thread)
    50     
    51     Test.print_cache()
    52     time.sleep(10)
    53     
    54     thread_pool = []
    55     for i in range(thread_num):
    56         th = threading.Thread(target=worker,args=[i, 100000])
    57         thread_pool.append(th)
    58         thread_pool[i].start()
    59 
    60     for thread in thread_pool:
    61         threading.Thread.join(thread)
    62     
    63     Test.print_cache()
    64     time.sleep(10)

    总结

    公用的数据,除非是只读的,不然不要当类成员变量,一是会共享,二是不好释放。

  • 相关阅读:
    Codeforces Round#410 Div.2
    AtCoder Beginner Contest-060
    如何将gedit变成c++编译器
    洛谷 P2486 [SDOI2011]染色
    让lu哥头痛了许久的代码(洛谷:树的统计)
    字符串模拟入门
    luogu P1553 数字反转(升级版)
    那些令人难忘的——坑
    luogu P1341 无序字母对
    最短路相关题目
  • 原文地址:https://www.cnblogs.com/2010Freeze/p/3162658.html
Copyright © 2011-2022 走看看