美文网首页Python3
Python thread demo

Python thread demo

作者: JaedenKil | 来源:发表于2019-07-19 18:01 被阅读0次
    from multiprocessing import Process, Queue
    from time import time
    
    
    def task_handler(current_list, result_queue):
        total = 0
        for n in current_list:
            total += n
        result_queue.put(total)
    
    
    def main():
        processes = []
        number_list = [x for x in range(1, 10000001)]
        result_queue = Queue()
        index = 0
        for _ in range(8):
            p = Process(target=task_handler, args=(number_list[index: index + 1250000], result_queue))
            index += 1250000
            processes.append(p)
            p.start()
        start = time()
        for p in processes:
            p.join()
        total = 0
        while not result_queue.empty():
            total += result_queue.get()
        print(total)
        end = time()
        print("Execution time: ", (end - start), 's', sep=' ')
    
    
    if __name__ == "__main__":
        main()
    
    50000005000000
    Execution time:  0.184340238571167 s
    

    相关文章

      网友评论

        本文标题:Python thread demo

        本文链接:https://www.haomeiwen.com/subject/gxnslctx.html