星星博客 »  > 

Python3 threading

python2中的thread在python3中升级成了threading ,原先的thread变成了_thread ,建议大家使用threading ,Python中虽然有GIL的存在,并不能并行线程,但是对于IO密集型的应用还是挺方便快捷的。
这里需要注意一个点:GIL并不能保证线程安全,看以下例子:
线程安全、非线程安全的相关概念
threading 并发针对同一个变量,需要加锁。
例子1:

import threading

num = 0

def task(count):
    global num
    for _ in range(count):
        num = num+1


if __name__ == '__main__':
    count = 1000000
    threads = []
    for _ in range(7):
        t1 = threading.Thread(target=task, args=(count,))
        t1.start()
        threads.append(t1)

    for t in threads:
        t.join()

    print(num)

当我们使用lock就可以避免这个问题:
例子2:

import threading

num = 0
lock = threading.Lock()


def task(count):
    global num, lock
    lock.acquire()
    for _ in range(count):
        num = num+1
    lock.release()


if __name__ == '__main__':
    count = 1000000
    threads = []
    for _ in range(7):
        t1 = threading.Thread(target=task, args=(count,))
        t1.start()
        threads.append(t1)

    for t in threads:
        t.join()

    print(num)

相关文章