目前我正在尝试使两个线程并行运行,但似乎发生的情况是要启动的第一个线程是唯一运行的线程。并行运行的Python线程
我的代码在下面列出,但最后更复杂,这是展示完全相同行为的示例代码。
如果我先启动第一个线程,命令行将重复打印“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工作正常。奇怪的。
如果人们对这个问题不满意,他们能否提供解释为什么?我看不出为什么这是一个糟糕的问题。 –