如何在Python代码中应用多处理?

2024-05-14 09:52:17 发布

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

我需要在代码中应用多重处理的帮助。我试着阅读Python文档的multiprocessing部分,但是我不知道如何将它应用到我所拥有的东西上。不过,我相信我想用的是游泳池。下面是我编写的一个python脚本的一部分,它最终将被另一个主脚本调用:

## servoRemote.py

from franges import drange
from cmath import sqrt as csqrt
from math import atan, degrees, radians, tan, sqrt, floor
import servo

# Declare variables for servo conditional statements:
UR = False
UL = False
BR = False
BL = False

def servoControl(x,y):
    global UR, UL, BR, BL
    ytop = round((-csqrt((0.3688**2)*(1-((x-0.5)**2)/(0.2067**2)))+0.5).real,3)
    ybottom = round((csqrt((0.3688**2)*(1-((x-0.5)**2)/(0.2067**2)))+0.5).real,3)

    if (x in list(drange(0.5,0.708,0.001,3)) and y in list(drange(ytop,0.501,0.001,3))):
        UR = True
        UL = False
        BR = False
        BL = False
        (factor, angle) = linearSF(x,y)
        (servo1, servo2) = angleSF(factor,angle)
        servo.move(1,servo1)
        servo.move(2,servo2)

def linearSF(r,s):
    # Calculates the hypotenuse of the gaze:
    distr = abs(r-0.4999)
    dists = abs(0.50-s)
    theta = atan(dists/distr)
    b = sqrt(distr**2+dists**2)

    # Involved in solving for max x coordinate:
    A = 1+0.31412198*tan(theta)**2
    B = (-1-0.31412198*tan(theta)**2)**2 - 4*(1+(tan(theta)**2)/3.183477)*(0.207275+0.0785305*tan(theta)**2)
    B = csqrt(B)
    C = 2+((2*tan(theta)**2)/3.183477)

    # Different x equations:
    xRight = ((A+B)/C).real
    xLeft = ((A-B)/C).real

    if (UR == True and UL == False and BR == False and BL == False):
        x = xRight
        y = -sqrt((0.3688**2)*(1-((x-0.5)**2)/(0.2067**2)))+0.5
    # Solve for max hypotenuse given an angle, a:
    a = sqrt(abs(x-0.5)**2+abs(0.5-y)**2)
    # Final outputs, factor and angle (in degrees):
    factor = (b/float(a))
    angle = degrees(theta)
    return (factor, angle)

def angleSF(factor, angle):
    # Angular factors:
    S1U = -0.0025641026*angle + 1.230759
    S2R = 0.0025641026*angle + 1
    if (UR == True and UL == False and BR == False and BL == False):
        servo1 = int(floor((S1U*65-78)*factor + 78))
        servo2 = int(floor((S2R*65-78)*factor + 78))
    return (servo1,servo2)

上面的代码只适用于UR==True的情况。还有其他条件if语句,它们后跟不同的条件。我发现的大多数使用多进程的示例都使用有限for循环,但我想把它放在下面的一段时间:

while 1:
    x = [some continuously incoming data stream]
    y = [some continuously incoming data stream]
    servoControl(x,y)

再次提前感谢!我相信,如果我了解如何为这一个脚本,我可能会想出如何将它应用到其他脚本。你知道吗


Tags: andbrimport脚本falsesqrtulfactor
1条回答
网友
1楼 · 发布于 2024-05-14 09:52:17

多重处理有点让人望而生畏。要理解的关键是,当其他进程正在使用一个资源(读或写)时,您不希望有多个进程使用该资源(例如,写入引用)。你知道吗

因此,对于理想的多处理设置,您希望每个进程只在它单独使用的资源上工作。你知道吗

因此,当1)多个进程在不同的资源上工作,2)您的硬件上有多个处理器,或者多个进程可以在单个(或多个)处理器机器上相互交换,同时等待事件发生时,可以有效地使用python中的多处理。你知道吗

我建议你用符合上述条件的“一些玩具”来体验它的工作原理和位置。然后重新审视您的问题,并尝试以与python多处理工作方式一致的方式实现它。你知道吗

仔细阅读文档。有一个join()函数,您可能需要确保在下一步之前完成所有进程,即使下一步只是终止程序。你知道吗

相关问题 更多 >

    热门问题