python - 为什么程序执行时间和以前一样?

标签 python python-multithreading

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

但是,如果我添加类似 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()

最佳答案

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

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

标准的解决方法是使用进程而不是线程。但这通常很痛苦,因为进程间通信并不那么容易。您可能还需要考虑使用一些低级库,例如 numpy,它们在某些情况下实际上会释放 GIL(您只能在 C 级别执行此操作,GIL 无法从 Python 本身访问)使用其他语言没有这个限制,例如C#、Java、C、C++ 等。

关于python - 为什么程序执行时间和以前一样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56529268/

相关文章:

python - 使 Python 'requests' 模块的连接池大小非常大有什么缺点?

Python: 'thread._local object has no attribute ' 待办事项'

Python 多线程/处理在 MySQL 中插入不同表的增益?

python - Django python paypalrestsdk - 没有 'Access-Control-Allow-Origin' 和 ppxo_unhandled_error 错误

python - python 3.5 的 Pygame 安装

python - MAC OS ImportError : pycurl: libcurl link-time version (7. 37.1) 早于编译时版本 (7.43.0)

python - 在 Python (Mac) 中使用 OpenCV 裁剪视频

python - 加快读取多个pickle文件

python - 为什么 concurrent.futures.ThreadPoolExecutor().submit 不立即返回?

javascript - 将 Django 模板转换为 pdf