Home > Enterprise >  Create two threads in python one to read and one to ask something
Create two threads in python one to read and one to ask something

Time:09-27

I would like to know if there is how to create two threads, one to ask some number and another to show this number typed in parallel.

from threading import Thread

global result
result = None


class OutPut(Thread):
    def __init__(self):
      Thread.__init__(self)

    def run(self):
      global result
      if result is not None:
          print('Number entered was: {}'.format(result))


class Write(Thread):
    def __init__(self):
      Thread.__init__(self);

    def run(self):
      global result
      user_write = True

      while user_write:
          num = int(input('Enter a number? '))
          result = num

          if num == 0:
              user_write = False


threadIO = Write()
threadOutPut = OutPut()

arrThread = [threadIO, threadOutPut]

for tH in arrThread:
  tH.start()

for t in arrThread:
  t.join()

print('===== THREADS OFF =====')

I was trying to do something with this code. The "thread" of asking until it works but showing what was typed doesn't.

CodePudding user response:

I still could not pin down your exact requirements, but I think what you need is something like this...

import time
import readline
import thread
import sys

global num
num = None

def print_num():
    while True:
        time.sleep(5)
        sys.stdout.write('\r' ' '*(len(readline.get_line_buffer()) 2) '\r')
        global num
        if num:
            print("Writing ", num)
        sys.stdout.write('Enter number > '   readline.get_line_buffer())
        sys.stdout.flush()

thread.Thread(target=print_num).start()

while True:
    num = input('Enter number > ')

CodePudding user response:

Here are some changes to your OutPut thread to print each result one time and also exit when 0 is input. The important part is that the OutPut thread must keep looping to check result, then reset result after printing it.

In your original code, you might consider putting a print at the end of OutPut's run function to see why the code doesn't work as you expected.

from threading import Thread

global result
result = None


class OutPut(Thread):
    def __init__(self):
        Thread.__init__(self)

    def run(self):
        global result
        while True: # Loop to check the result
            if result is not None:
                print("Number entered was: {}".format(result))
                if result == 0:
                    break  # if result is 0, break the loop
                result = None  # reset the result to None, so we don't print the same result again
        print("Thread finished")


class Write(Thread):
    def __init__(self):
        Thread.__init__(self)

    def run(self):
        global result
        user_write = True

        while user_write:
            num = int(input("Enter a number? "))
            result = num

            if num == 0:
                user_write = False


threadIO = Write()
threadOutPut = OutPut()

arrThread = [threadIO, threadOutPut]

for tH in arrThread:
    tH.start()

for t in arrThread:
    t.join()

print("===== THREADS OFF =====")
  • Related