python - 无法在Python中同时运行线程

标签 python multithreading python-2.7 python-multithreading frappe

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()

以上程序按顺序运行...

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 脚本来进行性能测试...为此我需要线程同时运行 有什么办法可以解决这个问题吗?

最佳答案

您的问题是 target= 关键字现在设置为函数的返回值。您想要函数本身。 所以,现在实际发生的事情是:

  1. 调用Function1()
  2. t1 将其目标设置为 None(Function1() 的返回值
  3. 针对 Function2()t2 重复 1-2。
  4. 启动 t1t2 线程,这两个线程都以 None 作为目标。这没有任何效果。

替换

t1= Thread(target=Function1())
t2= Thread(target=Function2())

t1= Thread(target=Function1)
t2= Thread(target=Function2)

如果您希望在多个内核上并行执行 Python 代码,那么您唯一的希望就是多处理。因为,正如另一个答案中提到的,CPython解释器只允许同时执行一段Python代码(参见“全局解释器锁”)。 网上可以找到很多这方面的信息。

关于python - 无法在Python中同时运行线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35890910/

相关文章:

java - 安全使用 CyclicBarrier.reset

python - 这是 linux 还是 virtualenv 错误?

python - 在带有 openpyxl 的 Python 中使用 Excel 命名范围

python - python文件输入模块中的 "input() already active"是什么意思?

Python Tkinter,通过在进入新窗口(新类)时引入变量来避免代码重复

python - fatal error : 'QTKit/QTKit.h' file not found when I build OpenCV on mac

django - 从 django 的 auth_user 表中删除用户

python - 更新到 VS Code 1.66.0 后调试 Python 程序不起作用

c# - 如何在 C# 中强制退出应用程序?

multithreading - 套接字 : how execute two threads simultaneously without stop?