Jump to content

Python: Difference between revisions

182 bytes added ,  11 December 2020
Line 337: Line 337:


executor = ThreadPoolExecutor(max_workers=2 * os.cpu_count())
executor = ThreadPoolExecutor(max_workers=2 * os.cpu_count())
thread_lock = threading.Lock()
sum = 0
def do_something(a, b):
def do_something(a, b):
   return a + b
   with thread_lock:
    sum += a + b
  return sum


futures = []
futures = []
Line 354: Line 359:
* Starting in Python 3.5, if <code>max_workers</code> is none, it defaults to <code>5 * os.cpu_count()</code>.
* Starting in Python 3.5, if <code>max_workers</code> is none, it defaults to <code>5 * os.cpu_count()</code>.
* <code>executor.shutdown()</code> will wait for all jobs to finish but you cannot submit any additional jobs from other threads, after calling shutdown.
* <code>executor.shutdown()</code> will wait for all jobs to finish but you cannot submit any additional jobs from other threads, after calling shutdown.
* List operations are thread-safe but most other operations will require using a thread lock or semaphore.


==Data Structures==
==Data Structures==