Python线程不并行运行

0 投票
1 回答
3686 浏览
提问于 2025-04-17 23:45

目前我正在尝试让两个线程同时运行,但似乎发生的情况是,第一个启动的线程是唯一一个在运行的。

下面是我的代码,虽然最终代码更复杂,但这是一个展示相同行为的示例代码。

如果我先启动第一个线程,命令行会不断打印“Here”,但从来不会打印“Here2”,反之亦然。

示例输出:

Attempt to handshake failed

Attempt to handshake failed
Attempt to handshake failed
here2
here2
here2
here2
here2
here2
here2
here2
here2
here2
here2

代码如下:

import serial
import time
import threading
from multiprocessing import Process
from datetime import datetime
from datetime import timedelta
from TableApps import *

#Temporary main function
def main(TTL):
    s = pySerial(TTL);
    count = 0;
    inc = 10;
    x = '';
    fac = None; #changed from '' to singleton "None", it's the coolest way to check for    nothingness -Abe
    while 1:
        if(s.teensyReady == False):
            time.sleep(1);
            print "Attempt to handshake failed";
            s.handshake();
        else:
            if(fac == None):
                fac = facade(s);
                thread = threading.Thread(getTouchData(fac));
                thread2 = threading.Thread(sendData(fac));
                thread2.start();
                thread.start();
           if(s.teensyReady == False):
                print fac.s.teensyReady;
                thread.join();
                thread2.join();

def getTouchData(fac):
    while 1:
        print "here2";
        time.sleep(0.1);
def sendData(fac):
    while 1:
        print "here";
        time.sleep(0.1);

谢谢大家!

编辑:

感谢roippi的帮助,我能够让这两个线程同时运行,不过在运行几秒钟后,一个线程似乎占据了主导地位,另一个线程就不再出现了。

简单来说,它的表现会像这样:

here
here2
here
here2
here
here2
here
here2
here
here
here
here
here
here
here
here
here
here
...

编辑2:

好的,似乎我解决了后续的问题。基本上在while循环中,我把条件改成了'threadStarted'来决定是否启动线程。此外,我在命令行中运行模块,而不是在IDLE中。

话虽如此,在我把其余代码整合进来后,在IDLE中运行也没问题。真奇怪。

1 个回答

6
threading.Thread(getTouchData(fac))

这不是正确调用 Thread 的方式。Thread 需要一个可调用的对象作为 target 参数,并且你需要把参数以元组的形式传递给 args 参数。总的来说:

threading.Thread(target=getTouchData, args=(fac,))

根据 文档

class threading.Thread(group=None, target=None, name=None, args=(), kwargs={})

这个构造函数应该始终使用关键字参数来调用。 参数包括:

target 是要通过 run() 方法调用的可调用对象。默认为 None,这意味着什么都不会被调用。

args 是传递给目标调用的参数元组。默认为 ()。

撰写回答