信号量输出错误

2024-03-29 07:45:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图让信号量在python中工作,但是由于某些原因,它们不能像我希望的那样工作。 我希望他们一次打印一个数字,比如:

sem1: 1
wait
sem2: 2
wait
sem1: 3
wait
sem2: 4

但结果是:

sem1: 1
sem2: 2
wait
sem1: 3
sem2: 4

这是我的密码:

import os, multiprocessing, time

sem1 = multiprocessing.Semaphore(1)
sem2 = multiprocessing.Semaphore(0)

pid1 = os.fork()
pid2 = -1

if pid1 != 0:
    pid2 = os.fork()
for i in range(1,20):
    if (i%2) == 1 and pid1==0:
            sem1.acquire()
            print("sem1: %d" %i)
            sem2.release()
            time.sleep(1)
    elif (i%2) == 0 and pid2==0:
            sem2.acquire()
            print("sem2: %d" %i)
            sem1.release()
            time.sleep(1)

我的想法有错吗?你知道吗


Tags: andreleaseiftimeosforkmultiprocessingprint
1条回答
网友
1楼 · 发布于 2024-03-29 07:45:47

time.sleep()需要从父进程调用才能实现功能。下面是修改后的代码,我相信这就是你想要的:

import os, multiprocessing, time

sem1 = multiprocessing.Semaphore(1)
sem2 = multiprocessing.Semaphore(0)

pid1 = os.fork()
pid2 = -1

if pid1 != 0:
    pid2 = os.fork()
for i in range(1,20):
    time.sleep(1)
    if (i%2) == 1 and pid1==0:
            sem1.acquire()
            print("sem1: %d" %i)
            sem2.release()
            #time.sleep(1)
    elif (i%2) == 0 and pid2==0:
            sem2.acquire()
            print("sem2: %d" %i)
            sem1.release()
            #time.sleep(1)

输出:

学期1:1

等等

学期2:2

等等

学期1:3

等等

学期2:4

等等

推理:

对单个子进程使用time.sleep(1)时,只有子进程睡眠,而不是父进程睡眠。当i为奇数时,它(对应的子进程)打印并进入睡眠状态,但父进程仍处于活动状态,并且当i为偶数时执行子进程。当i增加并且再次变为偶数时,它将等待直到睡眠周期完成。当我们在父级中调用thread.sleep(1)时,它会等待每个i值。你知道吗

相关问题 更多 >