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

 

posted @ 2018-11-17 00:35  漏斗倒过来  阅读(160)  评论(0编辑  收藏  举报