0

I want to add n natural numbers but divide it into different threads. I have implemented it. However, I am having a problem getting the sum in the end. Kindly help using synchronization, use a global variable and locking mechanism.

I have used threads. Lets suppose I want to add 30 natural numbers, and divide into three threads, each thread summing up 10 natural numbers, the answer I get is the sum of each thread, I want to get the sum of 30.

I am using Python 2.7

My code :

import threading


a=input("Enter first number")
b=input("Enter second number")

sum=0

def add_func(a,b):
    result=0
    for i in range(a, b+1):
        result =result + i
    print result

if __name__ == "__main__":
    t1 = threading.Thread(target=add_func(1, 10))
    t2 = threading.Thread(target=add_func(11, 20))
    t3 = threading.Thread(target=add_func(21, 30))


    t1.start()
    t2.start()
    t3.start()

OUTPUT :

Enter first number1
Enter second number30
55
155
255
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • Please try it yourself first and then share the problem you are facing. Thank you. – bumblebee Jun 13 '19 at 06:55
  • Check how to pass parameters to `add_funct`. And learn more about threading. Read [this](https://realpython.com/intro-to-python-threading/) – Pynchia Jun 13 '19 at 06:55
  • 1
    I don't understand why would you use threading for this. What it does is that it slows down the program. – Maximouse Jun 13 '19 at 07:58
  • @MaxiMouse Agreed! just wanted to implement. Thanks for the information, though – john_carter Jun 13 '19 at 09:32
  • 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) – ggorlen Jun 13 '19 at 17:56

1 Answers1

0

Even without the GIL (if you're in CPython), the threaded version of this problem is going to be slower than math, so I'm assuming this is purely for pedagogical purposes.

Threading in Python is primarily useful for IO-bound rather than CPU-bound work (but check out the multiprocessing module for CPU-bound work).

You can return results from threads in a variety of ways. One way is to pass in a result list and give each thread a unique id number which can be used to index into the list. When a thread finishes its task, it fills its bucket in the result list, which is available in the calling code after the threads all re-join.

Another way might be using a shared variable or lock to enforce mutual exclusion to shared data (if the GIL doesn't already do so...), but that feels like overkill for this situation.

Here's the code:

from threading import Thread
from math import ceil

def add_func(i, res, start, end):
    total = 0

    for n in range(start, end):
        total += n

    res[i] = total

if __name__ == "__main__":
    a = 67
    b = 131
    num_threads = 4
    threads = []
    res = [None] * num_threads
    step = ceil((b - a) / num_threads)

    for i in range(num_threads):
        t = Thread(
            target=add_func, 
            args=(i, res, a, min(b, a + step) + 1)
        )
        threads.append(t)
        t.start()
        a += step + 1

    for thread in threads:
        thread.join()

    print(sum(res))

Or here's the fast way for completeness on this particular problem:

a = 67
b = 130
print((abs(a - b) + 1) * (a + b) / 2)
ggorlen
  • 44,755
  • 7
  • 76
  • 106