Python多线程

多线程

Python3通过两个标准库提供对线程的支持:_thread  / threading



python中使用线程有两种方法:函数或者用类来包装线程对象
_thread:用函数来包装线程对象
threading:用类来包装线程对象



_thread
函数式:调用 _thread 模块中的 start_new_thread() 函数来产生新线程
参数说明:
    function -- 线程函数
    args -- 传递给线程函数的参数,他必须是 tuple 类型
    kwargs -- 可选参数



threading
threading除了包含 _thread 中所有的方法外,还提供了其他方法:
threading.currentThread():返回当前的线程变量
threading.enumerate:返回一个包含正在运行的线程list。包含:启动后,结束前;不包含:启动前,终止后.
threading.activeCount():返回正在运行的线程数量

除了使用方法外,线程模块还提供了 Thread 类来处理线程:
run():用以表示线程活动的方法
start():启动线程
join([time]):等待线程中止
isAlive():返回线程是否是活动的
getName():返回线程名
setName():设置线程名
 

# 使用 -thread 创建多线程

import _thread
from time import sleep
from datetime import datetime

def aa(name, tt):
    for i in range(3):
        sleep(tt)
        dd = datetime.now().strftime('%Y-%m-%d %H-%M-%S')
        print(f'{name}, {dd}
')


_thread.start_new_thread(aa, ('t1', 2))
_thread.start_new_thread(aa, ('t2', 4))




'''结果
t1, 2020-06-02 17-07-35

t2, 2020-06-02 17-07-37
t1, 2020-06-02 17-07-37


t1, 2020-06-02 17-07-39

t2, 2020-06-02 17-07-41

t2, 2020-06-02 17-07-45
'''

# 使用 threading 创建多线程

import threading
from time import sleep
from datetime import datetime

def aa(name, tt):
    for i in range(3):
        sleep(tt)
        dd = datetime.now().strftime('%Y-%m-%d %H-%M-%S')
        print(f'{name}, {dd}
')



t1 = threading.Thread(target=aa, args=('a1', 2))
t2 = threading.Thread(target=aa, args=('a2', 4))

t1.start()
t2.start()

t1.join()
t2.join()


'''结果

a1, 2020-06-02 17-17-50

a2, 2020-06-02 17-17-52
a1, 2020-06-02 17-17-52


a1, 2020-06-02 17-17-54

a2, 2020-06-02 17-17-56

a2, 2020-06-02 17-18-00

'''

多线程--锁

在多线程中,如果对同一个变量进行修改,会改变变量的值,这个时候我们就需要锁了

用法:

lock = threading.Lock()  # 创建锁
lock.acquire()           # 锁定
lock.release()           # 解锁
# 在没有使用锁的时候

import threading

num = 100


def cq(n:int):
    global num
    num += n
    num -= n


def run1(n:int):
    for i in range(100000):
        cq(n)


t1 = threading.Thread(target=run1, args=(2,))
t2 = threading.Thread(target=run1, args=(4,))


t1.start()
t2.start()

t1.join()
t2.join()


print(num)



'''结果
102
'''
# 使用锁后

import threading

num = 100
lock = threading.Lock()


def cq(n:int):
    global num
    num += n
    num -= n


def run(n:int):
    for i in range(100000):
        # 上锁
        lock.acquire()
        try:
            cq(n)
        finally:
            # 释放锁
            lock.release()


t1 = threading.Thread(target=run, args=(2,))
t2 = threading.Thread(target=run, args=(4,))


t1.start()
t2.start()

t1.join()
t2.join()


print(num)



'''结果
100
'''
原文地址:https://www.cnblogs.com/shiyixirui/p/13032430.html