多线程~锁~ProducerConsumer~队列

 1. 创建多线程

  方法1

  方法2

 2. 多线程共享全局变量以及锁

 3. Producer-Consumer model

 4. Queue队列

 

 

 

 

 

 

1. 创建多线程

方法1:

a 使用模块

import threading

b 调用  threading.Thread 方法

t1 = threading.Thread(target=coding)

c 使用start()方法开始线程

t1.start()
示例代码

 

方法2:

a 使用模块

import threading

b 使类继承自 threading.Thread   实现run方法

class CodingThread(threading.Thread):
    def run(self):
        pass

 c 使用start()方法开始线程

t1 = CodingThread()
t1.start()
#encoding: utf-8

import threading
import time

class CodingThread(threading.Thread):
    def run(self):
        for x in range(3):
            print('正在写代码%s' % threading.current_thread())
            time.sleep(1)


class DrawingThread(threading.Thread):
    def run(self):
        for x in range(3):
            print('正在画图%s' % threading.current_thread())
            time.sleep(1)

def main():
    t1 = CodingThread()
    t2 = DrawingThread()

    t1.start()
    t2.start()

if __name__ == '__main__':
    main()
示例代码

 

 2.多线程共享全局变量以及锁

线程锁创建锁方法

gLock = threading.Lock()

 

 开启锁

gLock.acquire()

 

释放锁

gLock.release()

 

#encoding: utf-8

import threading

VALUE = 0

gLock = threading.Lock()

def add_value():
    global VALUE
    gLock.acquire()
    for x in range(1000000):
        VALUE += 1
    gLock.release()
    print('value:%d'%VALUE)

def main():
    for x in range(2):
        t = threading.Thread(target=add_value)
        t.start()

if __name__ == '__main__':
    main()
示例代码

 

 

3.Producer-Consumer model

锁会引出生产者与消费者模型的概念,有两个版本,一个是使用threading.Lock()的版本,一个是使用threading.Condition()

Condition继承自Lock对锁进行了优化,使用 Condition.wait()方法,锁进行等待状态,Condition.notify_all()方法唤醒所有锁

#encoding: utf-8

import threading
import random
import time

gMoney = 1000
gLock = threading.Lock()
gTotalTimes = 10
gTimes = 0


class Producer(threading.Thread):
    def run(self):
        global gMoney
        global gTimes
        while True:
            money = random.randint(100,1000)
            gLock.acquire()
            if gTimes >= gTotalTimes:
                gLock.release()
                break
            gMoney += money
            print('%s生产了%d元钱,剩余%d元钱'%(threading.current_thread(),money,gMoney))
            gTimes += 1
            gLock.release()
            time.sleep(0.5)


class Consumer(threading.Thread):
    def run(self):
        global gMoney
        while True:
            money = random.randint(100,1000)
            gLock.acquire()
            if gMoney >= money:
                gMoney -= money
                print('%s消费者消费了%d元钱,剩余%d元钱' % (threading.current_thread(),money,gMoney))
            else:
                if gTimes >= gTotalTimes:
                    gLock.release()
                    break
                print('%s消费者准备消费%d元钱,剩余%d元钱,不足!'%(threading.current_thread(),money,gMoney))
            gLock.release()
            time.sleep(0.5)


def main():
    for x in range(3):
        t = Consumer(name='消费者线程%d'%x)
        t.start()

    for x in range(5):
        t = Producer(name="生产者线程%d"%x)
        t.start()

if __name__ == '__main__':
    main()
原始版生活者消息者
#encoding: utf-8

import threading
import random
import time

gMoney = 1000
gCondition = threading.Condition()
gTotalTimes = 10
gTimes = 0


class Producer(threading.Thread):
    def run(self):
        global gMoney
        global gTimes
        while True:
            money = random.randint(100,1000)
            gCondition.acquire()
            if gTimes >= gTotalTimes:
                gCondition.release()
                break
            gMoney += money
            print('%s生产了%d元钱,剩余%d元钱'%(threading.current_thread(),money,gMoney))
            gTimes += 1
            gCondition.notify_all()
            gCondition.release()
            time.sleep(0.5)


class Consumer(threading.Thread):
    def run(self):
        global gMoney
        while True:
            money = random.randint(100,1000)
            gCondition.acquire()
            while gMoney < money:
                if gTimes >= gTotalTimes:
                    gCondition.release()
                    return
                print('%s准备消费%d元钱,剩余%d元钱,不足!' % (threading.current_thread(),money,gMoney))
                gCondition.wait()
            gMoney -= money
            print('%s消费了%d元钱,剩余%d元钱' % (threading.current_thread(),money,gMoney))
            gCondition.release()
            time.sleep(0.5)


def main():
    for x in range(3):
        t = Consumer(name='消费者线程%d'%x)
        t.start()

    for x in range(5):
        t = Producer(name="生产者线程%d"%x)
        t.start()

if __name__ == '__main__':
    main()
Condition Implementing Producer-Consumer model

 

 

4. 队列Queue

在线程中,访问一些全局变量,加锁是一个经常的过程。如果你想把一些数据存储在某个队列中,那么Python内置了一个线程安全的模块

叫做queue模块。Python中的queue模块中提供了同步的,线程安全的队列类,包括FIFO(先进先出)队列Queue,LIFO(后入先出)队列

LifoQueue。这些队列都实现了锁原语(可以理解为原子操作,即要么不做,要么都做完),能够在多线程中直接使用。可以使用队列来实现

线程间的同步。相关的函数如下:

a. 初始化Queue(maxsize):创建一个先进先出队列

b. qsize():返回队列的大小

c. empth() : 判断队列是否为空

d. full():判断队列是否满

e. get():从队列中取最后一个数据

f. put():将一个数据放到队列中

#encoding: utf-8

from queue import Queue
import time
import threading

# q = Queue(4)
#
# for x in range(4):
#     q.put(x)
#
# for x in range(4):
#     print(q.get())

def set_value(q):
    index = 0
    while True:
        q.put(index)
        index += 1
        time.sleep(3)

def get_value(q):
    while True:
        print(q.get())

def main():
    q = Queue(4)
    t1 = threading.Thread(target=set_value,args=[q])
    t2 = threading.Thread(target=get_value,args=[q])

    t1.start()
    t2.start()

if __name__ == '__main__':
    main()
示例代码

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值