1

I have written a code which sums the elements of array and prints it using multithreading. But instead of using a global value I want to use a local one and return it. However as i use return the thread dies.Any idea on how to do it?

import threading
import time

total = 0

class myThread(threading.Thread):
    def __init__(self,threadId,name,starts,ends):
        threading.Thread.__init__(self)
        self.threadId = threadId
        self.name = name
        self.starts = starts
        self.ends = ends
    def run(self):
        print "strating " + self.name
        threadLock.acquire()
        calc_sum(self.starts,self.ends)
        threadLock.release()

def calc_sum(start,end):
    global total
    for i in xrange(start,end):
        total += arr[i]

threadLock = threading.Lock()
threads = []

arr = [1,2,3,4,5,6,7,8,9,10]

thread1 = myThread(1,'t1',0,5)
thread2 = myThread(2,'t2',5,10)

thread1.start()
thread2.start()

threads.append(thread1)
threads.append(thread2)

for t in threads:
    t.join()

print total
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555

1 Answers1

0

You are right, global variable is not the good solution. What about putting your result into self.total ? Then you access to your result like this :

for t in threads:
    total += t.total

print(total)
fjcf1
  • 150
  • 1
  • 1
  • 7
  • How can I access a thread like that as t.total. Could you explain me more clearly? – Raghuvardhan Karanam Jun 20 '17 at 10:27
  • threads is a list and by doing `for t in threads` you take one thread. Then you call your attribut total.Indeed, instead of saving your total in global total, you save it in self.total. – fjcf1 Jun 20 '17 at 12:40