Python is simple to use multi-threading

Python is simple to use multi-threading

The use of multiple threads simultaneously execute three functions, namely the use of sleep to add delay time to observe the end of the program the last execution time

# -*- coding:utf-8 -*-
import threading
import datetime
import time

locks = None


def unit_test(sleep):
    """
    多线程单元测试
    :param sleep: 等待的时间
    :return:
    """
    # locks.acquire()   获取锁 -- 获取锁之后,其他的线程在此等待
    print('start loop {}, '.format(sleep), datetime.datetime.now())
    time.sleep(sleep)
    print('loop {} down, '.format(sleep), datetime.datetime.now())
    # locks.release()   释放锁 -- 如果不释放锁,后续的线程会一直被阻塞不能进入


def thread_run(sleep_list):
    """
    运行多线程
    :param sleep_list: 延时时间列表
    :return:
    """
    global locks
    locks = threading.Lock()
    threads = []
    start_time = datetime.datetime.now()

    # insert all threads to threads list
    for i in sleep_list:
        t = threading.Thread(target=unit_test, args=(i,))
        threads.append(t)

    # start all threads
    for thread in threads:
        thread.start()

    # waiting all thread close
    for thread in threads:
        thread.join()

    end_time = datetime.datetime.now()
    print('所有线程结束,一共消耗{}秒钟'.format((end_time - start_time).seconds))


def main():
    sleep_list = [2, 4, 1]
    thread_run(sleep_list=sleep_list)


if __name__ == '__main__':
    main()

Results of the:

start loop 2,  2020-01-15 16:53:48.156806
start loop 4,  2020-01-15 16:53:48.156806
start loop 1,  2020-01-15 16:53:48.157804
loop 1 down,  2020-01-15 16:53:49.158589
loop 2 down,  2020-01-15 16:53:50.157596
loop 4 down,  2020-01-15 16:53:52.158573
所有线程结束,一共消耗4秒钟

As can be seen from the execution time of the program at the time of the call are performed simultaneously, sleep a maximum of 4 seconds, a total running time of the program takes only 4 seconds.

Published 27 original articles · won praise 10 · views 368

Guess you like

Origin blog.csdn.net/weixin_43750377/article/details/103992387