Junior — Middle
Have you had experience with multithreading or parallel computing?
sobes.tech AI
Answer from AI
Yes, I have experience working with multithreading and parallel computing in Python. For multithreading, the threading module is used, which allows running multiple threads within a single process. However, due to the GIL (Global Interpreter Lock), true parallelism in CPU-bound tasks is limited.
For parallel computations, it is better to use the multiprocessing module, which spawns multiple processes and bypasses GIL limitations.
Example of using threading:
import threading
def worker():
print("Thread is running")
threads = []
for i in range(5):
t = threading.Thread(target=worker)
t.start()
threads.append(t)
for t in threads:
t.join()
Example of using multiprocessing:
from multiprocessing import Pool
def f(x):
return x * x
if __name__ == '__main__':
with Pool(5) as p:
print(p.map(f, [1, 2, 3, 4, 5]))
Thus, the choice between threads and processes depends on the task and parallelism requirements.