2014-03-25 58 views
0

目前我正在尝试使两个线程并行运行,但似乎发生的情况是要启动的第一个线程是唯一运行的线程。并行运行的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工作正常。奇怪的。

+0

如果人们对这个问题不满意,他们能否提供解释为什么?我看不出为什么这是一个糟糕的问题。 –

回答

5
threading.Thread(getTouchData(fac)) 

这不是调用Thread的正确方法。 Thread需要收到可调用target kwarg,并且您需要将元组中的参数传递给 kwarg。总之:

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

docs

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

此构造应始终以关键字参数来调用。参数如下:

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

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

+0

谢谢,请参阅编辑;由于某种原因没有完全工作。 – mHo2

+0

恐怕这个问题是你在这里发布的代码的外部。上面的代码会产生两个无限循环的线程。由于我无法运行它,因此我无法帮助您进行调试。尝试创建一个最小的例子,然后添加事物,直到它断裂。 – roippi

+0

解决了,我想。如果您好奇,请参阅上文。 – mHo2