码迷,mamicode.com
首页 > 编程语言 > 详细

python3之线程

时间:2018-11-17 01:09:25      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:thread   def   线程   变量   reading   解决   print   竞争   random   

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

 

python3之线程

标签:thread   def   线程   变量   reading   解决   print   竞争   random   

原文地址:https://www.cnblogs.com/yan-peng/p/9972606.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!