-1

Here's my code.

import time    
import threading    
import multiprocessing

num1 = 0    
num2 = 0

def take_numbers(num1,num2):
    print('Enter the numbers:')
    for n in range(0,5):
        time.sleep(0.2)
        num1 = input('Enter first number')
        num2 = input('Enter second number')

def add_num(num1,num2):
     for n in range(0,5):
         time.sleep(0.2)
         return num1+num2

t1 = threading.Thread(target=take_numbers, args=(num1,num2))
t2 = threading.Thread(target=add_num, args=(num1,num2))
t1.start()
t2.start()
t1.join()
t2.join()

I need an output where it should stop when time.sleep(0.2) is called and perform addition with existing number and then again go to take_numbers function and get new numbers. I am only able to input the numbers but not getting an output. note:there is no problem with indentation.

Please help!! Thanks

  • 1
    Possible duplicate of [how to get the return value from a thread in python?](https://stackoverflow.com/questions/6893968/how-to-get-the-return-value-from-a-thread-in-python) – Karim N Gorjux Sep 16 '18 at 11:00
  • Why are you using threads to slow down your program? What were you hoping to achieve by using threads? – Aran-Fey Sep 16 '18 at 11:18
  • I have used two threads because when one is stopped the other should execute. – Shahbaz Khan Sep 16 '18 at 11:42
  • Let me make it clear,First i need to take an input from user.Then simultaneously perform addition over it and while performing addition the first one should take another input,either random input or user specific – Shahbaz Khan Sep 16 '18 at 11:44

1 Answers1

0

The input method should read the input and place it on queue. Add method will read input from queue and perform the operation. Here is the basic implementation -

import threading
from multiprocessing import Queue   

results = []

def take_numbers(q):
    print('Enter the numbers:')
    for i in range(0,5):
        num1 = int(input('Enter first number: '))
        num2 = int(input('Enter second number: '))
        q.put(num1)
        q.put(num2)

def add_num(q):
    for i in range(0,5):
        num1 = q.get()
        num2 = q.get()
        results.append(num1+num2)

q = Queue()
t2 = threading.Thread(target=add_num, args=(q, ))
t1 = threading.Thread(target=take_numbers, args=(q, ))

t2.start()
t1.start()
t2.join()
t1.join()
q.close()

for result in results:
    print ("result =", result)
Ajay Srivastava
  • 1,151
  • 11
  • 15
  • Thanks it worked for me!! I am also implementing parallel reduction in python using min,max and sum operations . If u can help me would be a great favor. Thanks – Shahbaz Khan Sep 16 '18 at 17:09
  • You can use similar logic as sum, for all reductions. If the number of input parameters vary, either put list of numbers as a single items on queue or use some kind of marker on queue to know the boundary of an input to the reduction function. – Ajay Srivastava Sep 17 '18 at 01:36