python threading Lock

这篇文章主要是通过代码说明:

  1. threading.Lock()不影响 multiprocessing.
  2. threading.Lock()影响 threading.

代码如下:

import threading
import time
from multiprocessing import Pool

_lock = threading.Lock()


def small_func(value):
    """
    添加线程锁
    :param value:
    :return:
    """
    print(value)
    with _lock:
        time.sleep(5)
    return value


def no_small_func(value):
    """
    没有线程锁
    :param value:
    :return:
    """
    print(value)
    # with _lock:
    time.sleep(5)
    return value


def main():
    """
    multiprocessing 是基于进程的,因此线程锁对其不影响,
    :return:
    """
    st = time.time()
    p = Pool(processes=4)
    value = p.map(func=small_func, iterable=range(4))
    et = time.time()
    print(f"all use time: {et - st}")
    print(value)


def main2():
    """
    threading 受到 线程锁 影响
    :return:
    """
    st = time.time()
    thread_list = []
    for temp_value in range(4):
        t = threading.Thread(target=small_func, args=(temp_value,))
        t.start()
        thread_list.append(t)

    for i in thread_list:
        i.join()

    et = time.time()
    print(f"all use time: {et - st}")
    # print(value)


def main3():
    st = time.time()
    thread_list = []
    res = []
    for temp_value in range(4):
        # 不加线程锁就行了
        t = threading.Thread(target=no_small_func, args=(temp_value,))
        t.start()
        thread_list.append(t)

    for i in thread_list:
        v = i.join()
        res.append(v)

    et = time.time()
    print(f"all use time: {et - st}")
    print(res)


if __name__ == '__main__':
    # main()
    # main2()
    main3()

你可能感兴趣的:(python,开发语言)