1. 程式人生 > >python3之執行緒

python3之執行緒

1執行緒的建立:

import threading
import time,random


def text1():
    while True:
        print(1111111)
        time.sleep(random.random()*2)

def text2():
    while True:
        print(2222222)
        time.sleep(random.random() * 2)
def main():
    # text1()
    # text2()

    #建立多執行緒
    t1 = threading.Thread(target=text1)
    t2 = threading.Thread(target=text2)
    t1.start()  #執行多執行緒
    t2.start()

if __name__ == "__main__":
    main()

 2互斥鎖:

在多執行緒之中全域性變數是共享的;在執行過程中又可能會發生資源競爭,所以會用到互斥鎖:比如

import threading
import time,os,random

num = 0
def text1(agr):
    global num
    for i in range(agr):
        num += 1
    print(num)

def text2(agr):
    global num
    for i in range(agr):
        num += 1
    print(num)


def main():

    t1 = threading.Thread(target=text1,args=(1000000,))
    t2 = threading.Thread(target=text2,args=(1000000,))
    t1.start()
    t2.start()

    time.sleep(5)
    print(num)

if __name__ == "__main__":
    main()

 執行結果:如下,而不是我們向看到的2000000

1170362
1302259
1302259

 如何解決呢,用到互斥鎖:

import threading
import time,os,random

num = 0
def text1(agr,mutex):
    global num
    for i in range(agr):
        mutex.acquire()  #上鎖
        num += 1
        mutex.release()  #解鎖
    print(num)

def text2(agr,mutex):
    global num
    for i in range(agr):
        mutex.acquire()  #上鎖
        num += 1
        mutex.release() #解鎖

    print(num)


def main():
    mutex = threading.Lock()  #建立一個互斥鎖
    t1 = threading.Thread(target=text1,args=(1000000,mutex))
    t2 = threading.Thread(target=text2,args=(1000000,mutex))
    t1.start()
    t2.start()

    time.sleep(5)
    print(num)

if __name__ == "__main__":
    main()

 結果:

1846157
2000000
2000000