Python: Difference between revisions

Line 299: Line 299:
list(b) # [0,1,2]
list(b) # [0,1,2]
</syntaxhighlight>
</syntaxhighlight>
==Multithreading==
===threading===
<code>import threading</code>
Use <code>threading.Thread</code> to create a thread.
===concurrrency===
<code>concurrency</code> gives you access to thread pools.
<syntaxhighlight lang="python">
import os
from concurrent import futures
from concurrent.futures import ThreadPoolExecutor
executor = ThreadPoolExecutor(max_workers=len(os.sched_getaffinity(0)))
def do_something(a, b):
  return a + b
 
futures = []
for i in range(5):
  future = self.executor.submit(do_something, 1, 2+i)
  futures.append(future)
</syntaxhighlight>
* <code>len(os.sched_getaffinity(0))</code> returns the number of threads available to the Python process
* Starting in Python 3.5, if <code>max_workers</code> is none, it defaults to 5 times the number of threads on the system.


==Classes==
==Classes==