为什么程序执行时间与之前相同?

2024-10-01 13:44:06 发布

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

由于某些原因,执行时间仍然与没有线程时相同

但是,如果我添加类似于time.sleep(secs)的内容,那么在目标def d中显然存在线程

def d(CurrentPos, polygon, angale, id):

    Returnvalue = 0
    lock = True
    steg = 0.0005
    distance = 0
    x = 0
    y = 0

    while lock == True:
        x = math.sin(math.radians(angale)) * distance + CurrentPos[0]
        y = math.cos(math.radians(angale)) * distance + CurrentPos[1]
        Localpoint = Point(x, y)
        inout = polygon.contains(Localpoint)
        distance = distance + steg
        if inout == False:
            lock = False

    l = LineString([[CurrentPos[0], CurrentPos[1]],[x,y]])
    Returnvalue = list(l.intersection(polygon).coords)[0]
    Returnvalue = calculateDistance(CurrentPos[0], CurrentPos[1], 
    Returnvalue[0], Returnvalue[1])

    with Arraylock:
        ReturnArray.append(Returnvalue)
        ReturnArray.append(id)



def Main(CurrentPos, Map):

    threads = []
    for i in range(8):
        t = threading.Thread(target = d, name ='thread{}'.format(i), args = 
        (CurrentPos, Map, angales[i], i))
        threads.append(t)
        t.start()
    for i in threads:
        i.join()

Tags: idtruelockdefmath线程distancepolygon
1条回答
网友
1楼 · 发布于 2024-10-01 13:44:06

欢迎来到the Global Interpreter Lock a.k.a. GIL的世界。您的函数看起来像是一个CPU绑定的代码(一些计算、循环、ifs、内存访问等)。抱歉,您不能使用线程来提高CPU受限任务的性能。这是Python的局限性

Python中有一些函数可以释放GIL,例如磁盘i/o、网络i/o和您实际尝试过的函数:sleep。实际上,线程确实提高了i/o绑定任务的性能。但在Python中,算术和/或内存访问不会并行运行

标准的解决方法是使用进程而不是线程。但是这通常是痛苦的,因为进程间的通信不是那么容易。您可能还想考虑使用一些像NoMy这样的低级库,这些文件实际上在某些情况下释放吉尔(只能在C级执行,吉尔不能从Python自己访问)<强>或< /强>使用其他一些没有此限制的语言,例如C++、java、C、C++等。p>

相关问题 更多 >