Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import logging
- import threading
- from concurrent.futures import ThreadPoolExecutor # Python 3.2
- import time
- import random
- counter = 0
- lock_counter = threading.Lock()
- # Test function
- def test(count):
- global counter
- global lock_counter
- threadname = threading.current_thread().name
- # logging.info(f'Starting: {threadname}')
- for x in range(count):
- logging.info(f'Count: {threadname} += {count}')
- # The global interpreter lock (GIL) in action
- counter = counter + 1
- # Locking
- # lock_counter.acquire()
- # lock_counter.acquire() #deadlock - waiting on resources
- # try:
- # counter += 1
- # finally:
- # lock_counter.release()
- # logging.info(f'Completed: {threadname}')
- # Main function
- def main():
- logging.basicConfig(format='%(levelname)s - %(asctime)s.%(msecs)03d: %(message)s',
- datefmt='%H:%M:%S',
- level=logging.DEBUG)
- logging.info('App Start')
- # initialize two workers.
- # initialize 4 iterations, in each calling the test function with a random value.
- # increment the global counter by 1 for 'random value' times..
- workers = 100
- with ThreadPoolExecutor(max_workers=workers) as ex:
- val = 10000
- results = [ex.submit(test, val) for x in range(workers * 2)]
- print(f'Counter: {counter}')
- logging.info('App Finished')
- if __name__ == "__main__":
- main()
Add Comment
Please, Sign In to add comment