fork download
  1. #!/usr/bin/env python3
  2. import time
  3. from threading import Thread
  4.  
  5. def task(tid):
  6. print("P({}) sleeping".format(tid))
  7. time.sleep(5)
  8. print( "P({}) entering CS".format(tid))
  9. # CS
  10. print( "P({}) exiting CS".format(tid))
  11.  
  12.  
  13. # Scan command line arguments
  14. thread_count = int( input() )
  15.  
  16. threads = [Thread(target=task, args=(tid,)) for tid in range(thread_count)]
  17. for t in threads:
  18. t.daemon = True # die if the program exits
  19. t.start() # start the thread
  20.  
  21. # wait for completion
  22. for t in threads: t.join()
Success #stdin #stdout 0.05s 30912KB
stdin
3
stdout
P(0) sleeping
P(1) sleeping
P(2) sleeping
P(0) entering CS
P(0) exiting CS
P(1) entering CS
P(1) exiting CS
P(2) entering CS
P(2) exiting CS