Click here to Skip to main content
14,447,082 members
Rate this:
Please Sign up or sign in to vote.
See more:
I met an issue with multiple threads in Python3. I want to compare the speed between single and multiple threads. But the time cost for a single thread is not correct I think, in the code below. It should be 2 seconds at least (because of GIL, the speed between single and multiple threads should be nearly the same in the code below), but it was nearly 0 seconds in fact. I found that the program does not enter to thread_job() function when execute main() function, why does this happen?

import threading
import time

def thread_job():
    for _ in range(5):
        time.sleep(2)

def main():
    for _ in range(5): #Activate 5 threads to execute the time wait job.        
        added_thread = threading.Thread(target = thread_job)
        added_thread.start()


if __name__ == '__main__':
    start = time.time()
    main()
    end = time.time()
    print("Mutiple thread takes " + str(end - start) + '\n') #calculate the time cost for multiple thread. it should be nearly 2 seconds in theory.

    start_1 = time.time()
    thread_job()
    end_1 = time.time()
    print("single thread takes " + str(end_1 - start_1) + '\n') #calculate the time cost for single thread. it should be nearly 10 seconds in theory.


What I have tried:

<pre>
Output:

Mutiple thread takes 0.0005013942718505859

single thread takes 10.002868175506592


The code was execute on windows Visual studio code .
Posted
Updated 7-Jul-19 22:17pm
Rate this:
Please Sign up or sign in to vote.

Solution 1

You are measuring the end time of the multi threaded test when all threads have started, not when they have finished. You need to add some sort of wait action in main to check when all the threads are complete.
   
Rate this:
Please Sign up or sign in to vote.

Solution 2

import threading
import time

def thread_job():
    for _ in range(5):
        time.sleep(2)

def main():
    for _ in range(5): #Activate 5 threads to execute the time wait job.        
        added_thread = threading.Thread(target = thread_job)
        added_thread.start()
        threads.append(added_thread)    

if __name__ == '__main__':
    threads = []
    start = time.time()
    main()
    end = time.time()
    for thread in threads:
        thread.join()      #should add join there wait all threads finished.
    print("Mutiple thread takes " + str(end - start) + '\n') #calculate the time cost for multiple thread. it should be nearly 2 seconds in theory.
    start_1 = time.time()
    thread_job()
    end_1 = time.time()
    print("single thread takes " + str(end_1 - start_1) + '\n') #calculate the time cost for single thread. it should be nearly 10 seconds in theory.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100