会员可以在此提问,百战程序员老师有问必答
对大家有帮助的问答会被标记为“推荐”
看完课程过来浏览一下别人提的问题,会帮你学得更全面
截止目前,同学们一共提了 132648个问题
Python 全系列/第三阶段:Python 网络与并发编程/并发编程 466楼

from multiprocessing import Process, Queue
from time import sleep
#encoding=utf-8


class MyProcess(Process):
    def __init__(self, name, mq):
        Process.__init__(self)
        self.name = name
        self.mq = mq

    def run(self):
        print(f'Process:{self.name},start')
        print(f'get Data:{self.mq.get()}')
        self.mq.put(self.name)
        sleep(3)
        print(f'Process:{self.name},end')


if __name__ == '__main__':
    mq = Queue()
    mq.put('1')
    mq.put('2')
    mq.put('3')
    p_list = []
    for i in range(3):
        p = MyProcess(f'p{i}',mq)
        p_list.append(p)
    for p in p_list:
        p.start()

C:\Users\kjin\PycharmProjects\pythonProject\venv\Scripts\python.exe C:\Users\kjin\PycharmProjects\pythonProject\queue.py 

Traceback (most recent call last):

  File "C:\Users\kjin\PycharmProjects\pythonProject\queue.py", line 21, in <module>

    mq = Queue()

         ^^^^^^^

  File "C:\Users\kjin\AppData\Local\Programs\Python\Python311\Lib\multiprocessing\context.py", line 102, in Queue

    from .queues import Queue

  File "C:\Users\kjin\AppData\Local\Programs\Python\Python311\Lib\multiprocessing\queues.py", line 21, in <module>

    from queue import Empty, Full

ImportError: cannot import name 'Empty' from 'queue' (C:\Users\kjin\PycharmProjects\pythonProject\queue.py)


Process finished with exit code 1

Python 全系列/第三阶段:Python 网络与并发编程/并发编程 467楼
Python 全系列/第三阶段:Python 网络与并发编程/网络通信 470楼
Python 全系列/第三阶段:Python 网络与并发编程/并发编程 471楼

count已经设置了全局变量,下面的为什么没反应,有没有什么方法可以让它也改变值

#coding=utf-8
from threading import Thread
from threading import Event
from time import sleep
from random import randint

global count #  设置了全局变量
def door():
    while True:

        if even.is_set():
            print("门已经开启,快进入")
            sleep(1)
            # even.wait
            if count > 3:
                print("超过3秒,门自动关闭")
                even.clear()
        else:
            count = 0
            print("门已关闭")
            # even.clear(): 写错了 ,门是被动的,人来了门就会开启,所以应该用wait.
            even.wait()
        count += 1


def person():
    num = 0
    while True:
        num += 1
        if even.is_set():

            print(f"门开着的,进去{num}人")
            count = 0 # 这个数值没办法给上面传输过去
        else:
            even.set()

            print(f"{num}刷卡开门通行")
        sleep(randint(1, 10))


if __name__ == "__main__":
    # 先开2个线程
    even = Event()
    t1 = Thread(target=door)
    t2 = Thread(target=person)
    t1.start()
    t2.start()


Python 全系列/第三阶段:Python 网络与并发编程/并发编程 475楼
Python 全系列/第三阶段:Python 网络与并发编程/网络通信 477楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

©2014-2025百战汇智(北京)科技有限公司 All Rights Reserved 北京亦庄经济开发区科创十四街 赛蒂国际工业园
网站维护:百战汇智(北京)科技有限公司
京公网安备 11011402011233号    京ICP备18060230号-3    营业执照    经营许可证:京B2-20212637