Discuss / Python / 这个代码运行之后,只执行了pw,好像pr没有执行啊。我的是win8.1系统。

这个代码运行之后,只执行了pw,好像pr没有执行啊。我的是win8.1系统。

Topic source

yang_sen

#1 Created at ... [Delete] [Delete and Lock User]
def write(q):
    print('Process to write: %s' % os.getpid())
    for value in ['A', 'B', 'C']:
        print('Put %s to queue...' % value)
        q.put(value)
        time.sleep(random.random())

# 读数据进程执行的代码:
def read(q):
    print('Process to read: %s' % os.getpid())
    while True:
        value = q.get(True)
        print('Get %s from queue.' % value)

if __name__=='__main__':
    # 父进程创建Queue,并传给各个子进程:
    q = Queue()
    pw = Process(target=write, args=(q,))
    pr = Process(target=read, args=(q,))
    # 启动子进程pw,写入:
    pw.start()
    # 启动子进程pr,读取:
    pr.start()
    # 等待pw结束:
    pw.join()
    # pr进程里是死循环,无法等待其结束,只能强行终止:
    pr.terminate()

返回结果:

Process to write: 8616 Put A to queue... Put B to queue... Put C to queue... [Finished in 2.6s]

Bgn-037

#2 Created at ... [Delete] [Delete and Lock User]

你再试试用命令行执行这个文件

流风浮叶

#3 Created at ... [Delete] [Delete and Lock User]

求问为啥在命令行里就可以显示出那个结果了?

陌涯_

#4 Created at ... [Delete] [Delete and Lock User]

同问

长风不落

#5 Created at ... [Delete] [Delete and Lock User]

只有在if name =='main'成立,也就是命令行调用的时候下面的代码才会执行啊,前面的的课程有讲过的,建议回去看看复习一下。


  • 1

Reply