进程同步和信号量 PV操作

本文通过Python模拟生产者消费者问题,探讨进程同步中的PV操作。解释了信号量机制,指出信号量大于0表示资源,小于0表示等待的进程。并以打水为例,详细说明了P(empty)和V(full)操作的逻辑,强调PV操作是走走停停的过程,且记录型信号量避免了满等现象。
摘要由CSDN通过智能技术生成

进程同步和PV操作理解


首先用python模拟了生产者消费者问题,代码如下:

import threading
import random

BUFFER_SIZE = 10
buffer = [[]] * 10
counter = 0
in_ = 0
out_ = 0
item = 0

def productor():
    global in_, buffer, counter, item
    while 1:
        # 发信号停
        while counter == BUFFER_SIZE:
            print("productor wait...\n")
        item = random.randint(1, 1000)
        buffer[in_].append(item)
        print("product {}\n".format(item))
        print("product counter {}\n".format(counter))
        in_ = (in_+1) % BUFFER_SIZE

        # 发信号走
        counter += 1


def customer():
    global out_, buffer, counter, item
    while 1:
        # 发信号停
        while counter == 0:
            print("customer wait...\n")

        item = buffer[out_].pop()
        print("custom {}\n".format(item))
        print("custom counter {}\n".format(counter))
      
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值