为什么我的代码不能在多个线程上工作?

时间:2019-05-31 16:40:52

标签: python python-3.x multithreading

我一直在尝试对我的代码进行多线程处理,但仍然可以使用,但是只使用了我CPU的15%(我有8个线程,因此只有1个线程)。

我尝试了许多脚本来从堆栈溢出和youtube进行多线程处理,但没有一个起作用。

import threading

n=2

def crazy():
    global n
    while True:
        n = n*2
        print(n)

threads = []
for i in range(4):
    t = threading.Thread(target=crazy)
    threads.append(t)
    t.start()

输出符合预期,但仅在一个线程上运行。

4 个答案:

答案 0 :(得分:0)

也许像这样:

from multiprocessing.dummy import Pool

n = 2


def crazy(_):
    global n
    while True:
        n = n * 2
        print(n)

threads = []
pool = Pool(8)
pool.map(crazy, range(8))
pool.close()
pool.join()

答案 1 :(得分:0)

这实际上是在使用线程(所有4个线程)。您可以通过在代码中实现暂停来进行测试:

import threading
import time

n = 2

def crazy():
    global n
    while True:
        n = n*2
        print(n)
        time.sleep(1) # pause

threads = []
for i in range(4):
    t = threading.Thread(target=crazy)
    threads.append(t)
    t.start()

首先打印的位置:

4
8
16
32

然后稍后再打印

64
128
256
512

它以4组为一组打印的事实证明4个线程正在运行,并且每个线程都在执行中遇到暂停。如果您试图最大化CPU使用率,那么多处理可能更符合您的需求? threading只是模仿一次发生的多件事,而multiprocessing实际上是一次完成多个事。请注意,多处理有些棘手,因为您必须聪明一些,以避免死锁。

答案 2 :(得分:0)

这正在运行多个python线程,但是python线程位于应用程序级别,而不是内核。这些应用程序线程轮流在同一内核上运行,但是它们确实是上下文切换。例如,获取此代码的输出。它在线程之间切换以打印数字:

import threading

n=0
def crazy(i):
    global n
    for i in range(4):
        n = n + 1
        print(f"Thread {i}: {n}")

threads = []
for i in range(4):
    t = threading.Thread(target=crazy, args=(i,))
    threads.append(t)
    t.start()

输出:

Thread 0: 1
Thread 1: 2
Thread 2: 3
Thread 3: 4
Thread 0: 5
Thread 1: 6
Thread 2: 7
Thread 3: 8
Thread 0: 9
Thread 1: 10
Thread 2: 11
Thread 3: 12
Thread 0: 13
Thread 1: 14
Thread 2: 15
Thread 3: 16

答案 3 :(得分:0)

全局解释器锁(GIL)不能与CPU速度提升相关联,您可以在https://realpython.com/python-gil/和google上了解有关GIL的信息

相关问题