简体   繁体   中英

How to make full use of CPU cores with threading in python 2

The following code seems to be executed sequentially rather than concurrently. And it only made use of one CPU core. Is there a way to make it use multiple cores or switch content between threads? (I hope it could work like Thread class in java.)

import threading 

def work(s) :
    for i in range(100) :
        print s
        for j in range (12345678) :
            pass

a = []
for i in range(3) :
    thd = threading.Thread(target = work('#'+str(i)))
    a.append(thd)

for k in a : k.start()
for k in a : k.join()

print "Ended."

Threads cannot utilize multiple cores in Python. Processes however can.

multiprocessing is a package that supports spawning processes using an API similar to the threading module. The multiprocessing package offers both local and remote concurrency, effectively side-stepping the Global Interpreter Lock by using subprocesses instead of threads. Due to this, the multiprocessing module allows the programmer to fully leverage multiple processors on a given machine. It runs on both Unix and Windows.

Click here for more information

A friend of mine asked me this once. In your case, just use multiprocessing.process and that will use all your cores.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM