-1

I trying to play around with multi-threading so I can better at it, but for some weird reason, my code doesn't want to follow the commands. It's suppose to go into a while loop and print, but it doesn't, and it's also not raising any errors, so which lines is the mistake on?

#!/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))
TeachAble
  • 17
  • 2

3 Answers3

1

Add this to the bottom:

while True:
   pass

The problem is that you're running off the bottom of your main program. This terminates the entire execution session.

Prune
  • 76,765
  • 14
  • 60
  • 81
1

Quick and short solution:

while True:
    time.sleep(1)

Do not use pass in the while loop, because it eats CPU. Expensive way of doing nothing.

If you want a more general solution, then you can import Tread from threading, then you can use join:

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()

This solution works also if the threads do not run endless, and your program can continue after the threads have finished.

quantummind
  • 2,086
  • 1
  • 14
  • 20
0

You can either do what Prune here suggested, or you can suspend the main thread after initiating DisplayA, DisplayB and DisplayC.

  • I am not using threading too much in python, but this might help you: http://stackoverflow.com/questions/529034/python-pass-or-sleep-for-long-running-processes –  Jun 28 '16 at 21:25