python 多线程知识

目录:https://blog.csdn.net/qq_30923243/article/details/83505907
启动一个线程
Python有两个模块:_thread(低级模块) 和threading(高级模块) ,大部分时候用threading

#coding:utf-8
import time,threading
#新线程执行的代码
def loop():
    print('thread %s is runing..' % threading.current_thread().name)
    n=0
    while n < 5:
        n = n + 1
        print('thread %s >>> %s' % (threading.current_thread().name,n))
        time.sleep(1)
        print('thread %s ended.' % threading.currentThread().name)
print('thread %s is runing' % threading.current_thread().name)
t=threading.Thread(target=loop, name="LoopThread")
t.start()
t.join()
print('thread %s ended.' % threading.current_thread().name)
#coding:utf-8
import time,threading
balance=0
def change_it(n):
    # 先存后取,结果应该为0:
    global balance
    balance = balance + n
    balance = balance - n

def run_thread(n):
    for i in range(100000):
        change_it(n)
th1 = threading.Thread(target=run_thread, args=(5,))
th2 = threading.Thread(target=run_thread, args=(8,))
th1.start()
th2.start()
th1.join()
th2.join()
print(balance) #结果不为0,因为多线程共享全局变量balance,th1、th2两个线程交替执行会不为0

多线程时确保一段代码不被打扰的执行,需要上锁

#coding:utf-8
import time,threading
balance=0
lock = threading.Lock()
def change_it(n):
    # 先存后取,结果应该为0:
    global balance
    balance = balance + n
    balance = balance - n

def run_thread(n):
    for i in range(100000):
        lock.acquire()
        try: #try  finally   确保锁一定会被释放
            change_it(n)
        finally:
            lock.release()
th1 = threading.Thread(target=run_thread, args=(5,))
th2 = threading.Thread(target=run_thread, args=(8,))
th1.start()
th2.start()
th1.join()
th2.join()

需注意避免死锁。俩人你拿我的我拿你的,都需要对方的东西才能离开,然后就尴尬了,锁上了。
python多线程无法利用多核的优势。

为了避免多线程共享全局变量 ThreadLocal相当于为每个线程创建出独立空间
ThreadLocal应用

# coding:utf-8
import threading
balance=0
local_num = threading.local()
def change_it(n):
    # 先存后取,结果应该为0:
    global balance
    local_num.balance = local_num.balance + n   # 这三行时,结果=0 
    local_num.balance = local_num.balance - n
    balance           = local_num.balance
    # balance = balance - n   # 此时结果不为0 -n +n顺序调换前后结果分别趋于正负
    # balance = balance + n   # 以后有时间找找原因(✪ω✪)
    # balance = balance

def run_thread(n):
    local_num.balance = 0
    for i in range(100000):
        change_it(n)
th1 = threading.Thread(target=run_thread, args=(5,))
th2 = threading.Thread(target=run_thread, args=(8,))
th1.start()
th2.start()
th1.join()
th2.join()
print(balance)

猜你喜欢

转载自blog.csdn.net/qq_30923243/article/details/85072496