欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python 线程冲突问题

程序员文章站 2023-12-31 13:16:52
...

线程冲突问题

# !/usr/bin/python
# -*- coding:utf-8 -*- 
# ++++++++++++++++++++
# author: FMspider
# time: 2018-5-3 10:15
# function: 线程冲突 
import threading

def addnum():
    global num
    # num -= 1

    tem = num
    print('ok')
    num = tem - 1

num = 100
threading_list = []

# 创建一百个线程,去执行addnum函数,addnum函数是一个-1的动作,按道理说执行结果会是 0

for i in range(100):
    t = threading.Thread(target=addnum)
    t.start()
    threading_list.append(t)

for t in threading_list: # 等待所有线程执行完毕
    t.join()
print(num)

运行结果:

python 线程冲突问题


解决办法,加一把锁

# !/usr/bin/python
# -*- coding:utf-8 -*- 
# ++++++++++++++++++++
# author: FMspider
# time: 2018-5-3 10:15
# function: 线程冲突, 加把锁
import threading

def addnum():
    global num
    # num -= 1

    r.acquire() # 获取锁   这个锁是锁的线程,防止CUP切换过快
    tem = num
    print('ok')
    num = tem - 1
    r.release() # 释放锁

num = 100
threading_list = []
r = threading.Lock()

# 创建一百个线程,去执行addnum函数
for i in range(100):
    t = threading.Thread(target=addnum)
    t.start()
    threading_list.append(t)

for t in threading_list: # 等待所有线程执行完毕
    t.join()
print(num)



上一篇:

下一篇: