What is the output of the following? “`python import threading results = [] lock = threading.Lock() def worker(n): with lock: results.append(n * 2) threads = [threading.Thread(target=worker, args=(i,)) for i in range(3)] for t in threads: t.start() for t in threads: t.join() print(sorted(results)) “`

Python Developer Hard

Python Developer — Hard

What is the output of the following? “`python import threading results = [] lock = threading.Lock() def worker(n): with lock: results.append(n * 2) threads = [threading.Thread(target=worker, args=(i,)) for i in range(3)] for t in threads: t.start() for t in threads: t.join() print(sorted(results)) “`

Key points

  • The lock prevents race conditions in multi-threaded environments.
  • Each thread appends a value to the results list.
  • The sorted results list is printed at the end.

Ready to go further?

Related questions