python 线程冲突问题

线程冲突问题

# !/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 线程冲突问题_第1张图片


解决办法,加一把锁

# !/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)



你可能感兴趣的:(python)