Home  >  Article  >  Backend Development  >  Sharing and releasing issues of python class variables under multi-threading

Sharing and releasing issues of python class variables under multi-threading

高洛峰
高洛峰Original
2016-10-18 10:32:201212browse

I was tricked by multi-threading recently. I didn’t realize that class variables are shared under multi-threading. Another thing is that I didn’t realize the memory release problem, which made me more tired.

1. Python class variables in multi-threading situation The ones below are shared

2. The release of python class variables in multi-threaded situations is incomplete

3. The part of the memory that python class variables have not released in multi-threaded situations can be reused

import threading
 import time
   
 class Test:
   
     cache = {}
       
     @classmethod
     def get_value(self, key):
         value = Test.cache.get(key, [])
         return len(value)
   
     @classmethod
     def store_value(self, key, value):
         if not Test.cache.has_key(key):
             Test.cache[key] = range(value)
         else:
             Test.cache[key].extend(range(value))
         return len(Test.cache[key])
   
     @classmethod
     def release_value(self, key):
         if Test.cache.has_key(key):
             Test.cache.pop(key)
         return True
   
     @classmethod
     def print_cache(self):
         print 'print_cache:'
         for key in Test.cache:
             print 'key: %d, value:%d' % (key, len(Test.cache[key]))
   
 def worker(number, value):
     key = number % 5
     print 'threading: %d, store_value: %d' % (number, Test.store_value(key, value))
     time.sleep(10)
     print 'threading: %d, release_value: %s' % (number, Test.release_value(key))
   
 if __name__ == '__main__':
     thread_num = 10
       
     thread_pool = []
     for i in range(thread_num):
         th = threading.Thread(target=worker,args=[i, 1000000])
         thread_pool.append(th)
         thread_pool[i].start()
   
     for thread in thread_pool:
         threading.Thread.join(thread)
       
     Test.print_cache()
     time.sleep(10)
       
     thread_pool = []
     for i in range(thread_num):
         th = threading.Thread(target=worker,args=[i, 100000])
         thread_pool.append(th)
         thread_pool[i].start()
   
     for thread in thread_pool:
         threading.Thread.join(thread)
       
     Test.print_cache()
     time.sleep(10)

Public Unless the data is read-only, do not use it as class member variables. First, it will be shared, and second, it will be difficult to release.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn