Search code examples
pythonmultithreadingpython-2.7concurrent-programming

Wait and notify multiple threads at the same time python


I am new to threading and python and I want to hit a server with multiple (10) http requests at the same time. I have a utility for sending the request. I wrote a code as follows:

import time
import threading

def send_req():
    start = time.time()
    response = http_lib.request(ip,port,headers,body,url)
    end = time.time()
    response_time = start - end
    print "Response Time: ", response_time

def main():
    thread_list = []
    for thread in range(10):
        t = threading.Thread(target=send_req)
        t.start()
        thread_list.append(t)

    for i in thread_list:
        i.join()

if (__name__ == "__main__"):
    main()

It runs and prints out the response times. But then, since I am creating the threads one after the other their execution seems to be sequential and not concurrent. Can I create 10 threads at the same time and then let them execute together or create threads one by one keeping the created ones on wait until they are all finished creating and then execute them at the same time?


Solution

  • What do you mean by "at the same time" ?, threads do work in parallel behavior but you cannot start the threads at same exact time because python is a scripting language n its executes line by line.

    however, One possible solution is, you can start the threads one by one, then inside the threads, you wait for some flag to trigger and keep that flag global in all of your created threads. As that flag gets True, your threads will start their process at same time. Make sure to trigger that flag=True AFTER starting all of the threads. i.e.;

    def send_req():
        global flag
        while flag==False:
            pass          # stay here unless the flag gets true
        start = time.time()
        response = http_lib.request(ip,port,headers,body,url)
        end = time.time()
        response_time = start - end
        print "Response Time: ", response_time
        run_once=True
    
    def main():
     flag=False
     thread_list = []
     for thread in range(10):
        t = threading.Thread(target=send_req)  # creating threads one by one
        #t.start()
        thread_list.append(t)
    
     for j in thread_list:   # now starting threads (still one by one)
        j.start()
    
     flag=True      # now start the working of each thread by releasing this flag from False to true     
    
     for i in thread_list:
        i.join()