Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
177 views
in Technique[技术] by (71.8m points)

multithreading - Python: Understanding Threading Module

While learning Python's threading module I've run a simple test. Interesting that the threads are running sequentially and not parallel. Is it possible to modify this test code so a program executes the threads in same fashion as multiprocessing does: in parallel?

import threading

def mySlowFunc(arg):
    print "
Starting...", arg
    m=0
    for i in range(arg):
        m+=i
    print '
...Finishing', arg

myList =[35000000, 45000000, 55000000]

for each in myList:
    thread = threading.Thread(target=mySlowFunc, args=(each,) )
    thread.daemon = True
    thread.start()
    thread.join()

print "
 Happy End 
"

REVISED CODE:

This version of the code will initiate 6 'threads' running in 'parallel'. But even while there will be 6 threads only two CPU's threads are actually used (6 other Physical CPU threads will be idling and doing nothing).

import threading

def mySlowFunc(arg):
    print "
Starting " + str(arg) + "..."
    m=0
    for i in range(arg):
        m+=i
    print '
...Finishing ' + str(arg)

myList =[35000000, 45000000, 55000000, 25000000, 75000000, 65000000]


for each in myList:
    thread = threading.Thread(target=mySlowFunc, args=(each,) )
    thread.daemon = False
    thread.start()

print "
 Bottom of script reached 
"
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

From the docs for the join method:

Wait until the thread terminates. This blocks the calling thread until the thread whose join() method is called terminates – either normally or through an unhandled exception – or until the optional timeout occurs.

Just create a list of threads and join them after launching every single one of them.

Edit:

The threads are executing in parallel, you can think of python's threads like a computer with a single core, the thing is, python's threads are best for IO operations (reading/writing a big file, sending data through a socket, that sort of thing). If you want CPU power you need to use the multiprocessing module


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...