无法在 python 中同时 运行 个线程
not able to run threads simultaneosly in python
from threading import Thread
import time
def Function1():
print "11"
print "12"
time.sleep(5)
print "13"
print "14"
def Function2():
print "21"
print "22"
time.sleep(10)
print "23"
print "24"
for i in range(3)
t1= Thread(target=Function1())
t2= Thread(target=Function2())
t1.start()
t2.start()
以上程序依次 运行s...
11
12
13
14
21
22
23
24
11
12
13
14
21
22
23
24
11
12
13
14
21
22
23
24
如何运行同时执行两个函数(线程)??我不想使用多处理..
我需要编写 python 性能测试脚本...为此我需要线程同时 运行
有什么办法可以解决这个问题吗?
how to run two functions(threads) simultaneously? I don't want to use multiprocessing..
不幸的是,你不能真正同时拥有这两个(或者至少,你不能 运行 真正同时使用 threading
的东西)。这是一个 inherent limitation of the CPython interpreter's GIL.
threading
唯一提供的是单核上下文切换,其中解释器将 运行 单核上的一个函数,然后暂时将其换出并 运行 一个单核上的不同功能等。这对于在执行某些操作时可能很有用,例如,监视用户输入,但仅此而已。
您的问题是 target=
关键字现在设置为 函数的 return 值 。您想要函数本身。
所以,现在实际发生的是:
- 致电
Function1()
t1
的目标设置为 None
(Function1()
的 return 值
- 1-2 重复
Function2()
和 t2
。
- 启动
t1
和 t2
线程,它们都以 None
作为目标。这没有效果。
替换
t1= Thread(target=Function1())
t2= Thread(target=Function2())
和
t1= Thread(target=Function1)
t2= Thread(target=Function2)
如果你想在多核上并行执行 Python 代码,那么你唯一的希望就是 multiprocessing
。因为,正如在另一个答案中提到的,CPython 解释器只允许同时执行一段 Python 代码(参见 "Global Interpreter Lock")。
网上可以查到很多这方面的资料。
from threading import Thread
import time
def Function1():
print "11"
print "12"
time.sleep(5)
print "13"
print "14"
def Function2():
print "21"
print "22"
time.sleep(10)
print "23"
print "24"
for i in range(3)
t1= Thread(target=Function1())
t2= Thread(target=Function2())
t1.start()
t2.start()
以上程序依次 运行s...
11
12
13
14
21
22
23
24
11
12
13
14
21
22
23
24
11
12
13
14
21
22
23
24
如何运行同时执行两个函数(线程)??我不想使用多处理.. 我需要编写 python 性能测试脚本...为此我需要线程同时 运行 有什么办法可以解决这个问题吗?
how to run two functions(threads) simultaneously? I don't want to use multiprocessing..
不幸的是,你不能真正同时拥有这两个(或者至少,你不能 运行 真正同时使用 threading
的东西)。这是一个 inherent limitation of the CPython interpreter's GIL.
threading
唯一提供的是单核上下文切换,其中解释器将 运行 单核上的一个函数,然后暂时将其换出并 运行 一个单核上的不同功能等。这对于在执行某些操作时可能很有用,例如,监视用户输入,但仅此而已。
您的问题是 target=
关键字现在设置为 函数的 return 值 。您想要函数本身。
所以,现在实际发生的是:
- 致电
Function1()
t1
的目标设置为None
(Function1()
的 return 值
- 1-2 重复
Function2()
和t2
。 - 启动
t1
和t2
线程,它们都以None
作为目标。这没有效果。
替换
t1= Thread(target=Function1())
t2= Thread(target=Function2())
和
t1= Thread(target=Function1)
t2= Thread(target=Function2)
如果你想在多核上并行执行 Python 代码,那么你唯一的希望就是 multiprocessing
。因为,正如在另一个答案中提到的,CPython 解释器只允许同时执行一段 Python 代码(参见 "Global Interpreter Lock")。
网上可以查到很多这方面的资料。