线程锁、线程队列、yield

1.  线程锁:当有一个数据有多个线程对其进行修改的时候,任意个线程改变它都会对其他线程造成影响。如果想在某一个线程使用完之前,其他线程不能对其进行修改,就需要对这个线程加一个线程锁。

import threading
import time
import random

count = 0
def get_money(money):
    global count
    count += money
    count += money
    count -= money
# 创建一个线程锁对象
lock = threading.Lock()
def lock_thread(money):
    # acquire捕获
    lock.acquire()
    time.sleep(random.randint(1,3))
    print('当前线程为',threading.current_thread().name)

    get_money(money)
    time.sleep(random.randint(1, 3))
    print('当前线程为', threading.current_thread().name)
    # 解锁
    lock.release()

# 创建线程的参数为一个元组类型 args必须为一个可叠加对象
# 主线程 开辟一个分线程
thread1 = threading.Thread(target=lock_thread,name='thread1',args=(1000,))
thread2 = threading.Thread(target=lock_thread,name='thread2',args=(2000,))
thread1.start()
thread2.start()
print('hello world')

线程锁和join的区别:

join :注重的是整体,线程1没执行完,线程2不能执行;

线程锁 : 注重的是局部,某一个变量没执行完,其他的不能执行。

2.  线程队列:

# queue 队列
import queue
# 创建一个线程队列
# 队列:FIFO frist in frist OUT 先进先出
q = queue.Queue()
for i in range(5):
    # 将内容放入到线程队列中
    q.put(i)
while not q.empty():
    # get 得到
    print(q.get())
# Lifo last in frist out 后进先出
p = queue.LifoQueue()
for i in range(5):
    p.put(i)
while not p.empty():
    print(p.get())

例子 : 利用上述内容,写一个卖票系统:

import threading
import time
import random

class buyer(object):
    def __init__(self,name = '',number = 1 ):
        self.number = number
        self.name = name
lock = threading.Lock()
class computer(object):
    def __init__(self,count = 0):
        self.count = count
    def query_with_buyer_info(self,other):

        print('正在为{}查询剩余票数'.format(other.name))
        time.sleep(random.randint(1,3))
        lock.acquire()
        if self.count > other.number:
            print('有票,{}可以买'.format(other.name))
            time.sleep(random.randint(1,3))
            self.count -=other.number
        else:
            print('没票')
        lock.release()
hanmeimei = buyer('韩梅梅',2)
houzi = buyer('猴子',5)

com = computer(6)
thread1 = threading.Thread(target=com.query_with_buyer_info,name='thread1',args=(hanmeimei,))
thread2 = threading.Thread(target=com.query_with_buyer_info,name='thread2',args=(houzi,))

thread1.start()
thread2.start()

3.yield

def test1(name):
    print('return方法')
    return name
    print('return方法结束')
name = test1('zhangsan')
print(name)

def test2(age):
    for i in range(age):
        yield i
        print('hello')
for x in test2(18):
    print('x=',x)

return 与yield 的区别:

return 可以往方法外传递一个值,return之后的代码统统不执行

yield 也可以往方法外传递值,但是传递之后,代码回到yield的后面继续执行。同时,通过yield传递值,是一个可迭代的对象。

猜你喜欢

转载自blog.csdn.net/weixin_42657103/article/details/81349806