LiorA100

p46

Nov 13th, 2021 (edited)
351
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.48 KB | None | 0 0
  1. import logging
  2. import threading
  3. from concurrent.futures import ThreadPoolExecutor  # Python 3.2
  4. import time
  5. import random
  6.  
  7. counter = 0
  8. lock_counter = threading.Lock()
  9.  
  10.  
  11. # Test function
  12. def test(count):
  13.     global counter
  14.     global lock_counter
  15.     threadname = threading.current_thread().name
  16.     # logging.info(f'Starting: {threadname}')
  17.  
  18.     for x in range(count):
  19.         logging.info(f'Count: {threadname} += {count}')
  20.  
  21.         # The global interpreter lock (GIL) in action
  22.         counter = counter + 1
  23.  
  24.         # Locking
  25.         # lock_counter.acquire()
  26.         # lock_counter.acquire() #deadlock - waiting on resources
  27.         # try:
  28.         #    counter += 1
  29.         # finally:
  30.         #    lock_counter.release()
  31.  
  32.     # logging.info(f'Completed: {threadname}')
  33.  
  34.  
  35. # Main function
  36. def main():
  37.     logging.basicConfig(format='%(levelname)s - %(asctime)s.%(msecs)03d: %(message)s',
  38.                         datefmt='%H:%M:%S',
  39.                         level=logging.DEBUG)
  40.     logging.info('App Start')
  41.  
  42.     # initialize two workers.
  43.     # initialize 4 iterations, in each calling the test function with a random value.
  44.     # increment the global counter by 1 for 'random value' times..
  45.  
  46.  
  47.     workers = 100
  48.     with ThreadPoolExecutor(max_workers=workers) as ex:
  49.         val = 10000
  50.         results = [ex.submit(test, val) for x in range(workers * 2)]
  51.  
  52.     print(f'Counter: {counter}')
  53.     logging.info('App Finished')
  54.  
  55.  
  56. if __name__ == "__main__":
  57.     main()
Add Comment
Please, Sign In to add comment