Advertisement
GoodiesHQ

Threading_Tutorial_03.py

Oct 6th, 2017
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.53 KB | None | 0 0
  1. import threading
  2.  
  3. i = 0
  4. THREAD_CNT = 10
  5. LOOP_CNT = 50000
  6.  
  7. def foo():
  8.     """This will increment the global variable i in a thread unsafe way"""
  9.     global i
  10.     for _ in range(LOOP_CNT):
  11.         i += 1  # increments the global variable
  12.  
  13. threads = [threading.Thread(target=foo) for _ in range(THREAD_CNT)]
  14. for t in threads:
  15.     t.start()  # starts each thread
  16.  
  17. for t in threads:
  18.     t.join()  # waits for each thread to complete execution
  19.  
  20. print("Expected: ".ljust(10), len(threads) * LOOP_CNT)
  21. print("Actual: ".ljust(10), i)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement