python - 我不能在python中启动两个并行线程吗,每个线程都有一个forerver循环

标签 python multithreading

我有一个简单的Python3代码,我想启动这两个函数,但只运行“from_1”。 问题:如何在没有 .sleep() 函数的情况下管理两个线程,Python 有什么需要管理的吗?

import threading
def from_1():
    i = 1
    while True:
        print("Thread 1 {}".format(i))
        f = open('face1.jpeg','rb')
        img = f.read()
        f = open('face1_w.jpeg','wb')
        f.write(img)
        f.close()
        i += 1
def from_2():
    i = 1
    while True:
        print("Thread 2 {}".format(i))
        f = open('face2.jpeg','rb')
        img = f.read()
        f = open('face2_w.jpeg','wb')
        f.write(img)
        f.close()
        i-= 1
if __name__ == '__main__':
    jobs = []
    threading.Thread(from_1()).start()
    threading.Thread(from_2()).start()
    

enter image description here

最佳答案

在Python中,线程构造函数应该总是使用关键字参数来调用。因此,为了让您的程序正常工作,您需要 target 关键字来指向线程需要运行的函数。

import threading
def from_1():
    i = 1
    while True:
        print("Thread 1 {}".format(i))
        f = open('face1.jpeg','rb')
        img = f.read()
        f = open('face1_w.jpeg','wb')
        f.write(img)
        f.close()
        i += 1
def from_2():
    i = 1
    while True:
        print("Thread 2 {}".format(i))
        f = open('face2.jpeg','rb')
        img = f.read()
        f = open('face2_w.jpeg','wb')
        f.write(img)
        f.close()
        i-= 1
if __name__ == '__main__':
    jobs = []
    threading.Thread(target=from_1).start()
    threading.Thread(target=from_2).start()

关于python - 我不能在python中启动两个并行线程吗,每个线程都有一个forerver循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63790078/

相关文章:

python - 如何为 tensorflow 多GPU代码实现批量归一化层

python - ValueError : Input shapes do not overlap raster. Geopandas/Rasterio,屏蔽时可能出现 CRS 错误

python - 如何在测试集中找到错误的预测案例(使用 Keras 的 CNN)

Linux 中的 C++ 线程

c# - 我该如何解决这个线程问题?

python - 如何使用 pandas 查找内存泄漏

python - 选择同名的 2nd DIV CLASS - Python Selenium

java - 每个 JVM 或每个 CPU 核心的线程数

c++ - FAST DMA 受益于在 C++ 中使用线程的 FPGA

multithreading - 咖啡文档 :"Use multiple classification threads to ensure the GPU is always fully utilized"。如何?