1

I am trying to create different threads to work with 8 cores. However I see the code creates 8 threads but only uses around on 100% on my macos. Why?

def runner(i):
    # do random stuff
    for a in range(0,1000000):
        i+=1
        5000 / 34 * i
        i + 400
        i / 20000
        i * 24440
        i+=1
        5000 / 34 * i
        i + 400
        i / 20000

q = queue.Queue()
threads = list()
for x in range(0,80):
    th = threading.Thread(target=runner,args=(x,))
    threads.append(th)

for th in threads:
    th.start()
for th in threads:
    th.join()
1

1 Answer 1

2

This is due to Python GIL (Global Interpreter Lock). It blocks Python threads to work on a single CPU. You can read more about it at https://wiki.python.org/moin/GlobalInterpreterLock

Python GIL is a mutex that protects access to Python objects, preventing multiple threads from executing Python bytecodes at once. This lock is necessary mainly because CPython's memory management is not thread-safe.

There are multiple questions on the subject, check out the list here on SO

If you want your code to work on multiple CPUs, check out the multiprocessing module.

Sign up to request clarification or add additional context in comments.

7 Comments

Or you can disable GIL, but it's not so safety :)
@ArtsiomPraneuski in what ways is it safe to disable the GIL?
@ArtsiomPraneuski that's really not a good advice
where did I write that this is safe :)
@Vinny yeah, I know. that's why I left smile there :)
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.