Возможно ли выполнение потоков на отдельных ядрах CPU в рамках одного процесса?
sobes.tech AI
Answer from AI
In Python, the standard implementation CPython uses a global interpreter lock (GIL), which prevents multiple threads from executing Python bytecode simultaneously on different CPU cores within a single process. This means that threads within the same process cannot efficiently run in parallel on different cores when performing Python computations.
However, if threads perform I/O operations or invoke C extensions that release the GIL, they can run in parallel on different cores.
For true parallelism on multiple cores, the multiprocessing module is typically used, which creates separate processes, each with its own interpreter and memory.
Example of using multiprocessing:
from multiprocessing import Pool
def f(x):
return x * x
if __name__ == '__main__':
with Pool(4) as p:
print(p.map(f, [1, 2, 3, 4]))
Thus, threads within a single process do not guarantee execution on different cores due to the GIL, but processes do.