2016-06-28 58 views
-1

我想玩多線程,所以我可以做得更好,但由於一些奇怪的原因,我的代碼不想遵循命令。它假設進入while循環並打印,但它不會,並且也不會產生任何錯誤,所以哪些行是錯誤的?我在這個python腳本中犯了什麼錯誤?

#!/usr/bin/env python 
# 
# 
# 
import random 
import thread 
import time 
import sys 
import os 


def DisplayA(name,wait): 
    while True: 
     print 'Display: 1';time.sleep(wait) 


def DisplayB(name,wait): 
    while True: 
     print 'Display: 2';time.sleep(wait) 


def DisplayC(name,wait): 
    while True: 
     print 'Display: 3';time.sleep(wait) 



thread.start_new_thread(DisplayA,('Display1',2)) 
thread.start_new_thread(DisplayB,('Display2',3)) 
thread.start_new_thread(DisplayC,('Display3',5)) 
+0

這從我的終端正常工作...... ... –

+0

你看到的輸出是什麼?一點都沒有?另外,哪個版本的Python,在哪個操作系統上? –

回答

1

一下添加到底部:

while True: 
    pass 

的問題是,你運行了你的主程序的底部。這會終止整個執行會話。

+0

這是一個吞噬CPU的無限循環。 – quantummind

+0

對......這只是一個簡單的例子。你的迴應是一個明顯的改進。 – Prune

0

您可以執行Prune在此處建議的操作,也可以在啓動DisplayA,DisplayB和DisplayC後暫停主線程。

+0

你能展示如何掛起主線程嗎? –

+0

我沒有在Python中使用線程,但是這可能對你有所幫助:http://stackoverflow.com/questions/529034/python-pass-or-sleep-for-long-running-processes – 2016-06-28 21:25:29

1

快速和簡短的解決方案:

while True: 
    time.sleep(1) 

不要在while循環使用合格的,因爲它吃CPU。 昂貴的無所作爲的方式。

如果你想要一個更通用的解決方案,那麼你可以從線程導入花紋,那麼你可以使用加入:

from threading import Thread 
... 

p1 = Thread(name="A", target=DisplayA, args=('Display1',2)) 
p2 = Thread(name="B", target=DisplayB, args=('Display2',3)) 
p3 = Thread(name="C", target=DisplayC, args=('Display3',5)) 
p1.start() 
p2.start() 
p3.start() 

p1.join() 
p2.join() 
p3.join() 

此解決方案也如果線程不運行無止境的,你的程序可以繼續線程完成後。

相關問題