How to do multithrading of a simple function? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: How to do multithrading of a simple function? (/thread-6345.html) |
How to do multithrading of a simple function? - ratanbhushan - Nov-17-2017 Hi Team I have a simple code in python which is below: import threading from random import * class cal(): def __init__(self,a,b): self.a=a self.b=b def add(self): return self.a+self.b for i in range(10000): a = randint(1,10) b = randint(1,10) obj = cal(a,b) print(a,'+',b,'=',obj.add()) Please advise how to achieve above using multi threading as if we run the above program in at least 10 parallel program, how to do that? import threading from random import * class cal(): def __init__(self,a,b): self.a=a self.b=b def add(self): return self.a+self.b for i in range(10): a = randint(1,10) b = randint(1,10) obj = cal(a,b) print(a,'+',b,'=',obj.add()) RE: How to do multithrading of a simple function? - heiner55 - Nov-17-2017 #!/usr/bin/python3 import threading, time from random import * class cal(): def __init__(self, i, a, b): self.i = i self.a = a self.b = b def add(self, c): print("thread", self.i, "starts", self.a, self.b, c) time.sleep(2) s = self.a + self.b + c print("thread", self.i, "ends: ", self.a, self.b, c, "sum: ", s) for i in range(10): a = randint(1, 10) b = randint(1, 10) c = randint(1, 10) obj = cal(i, a, b) t = threading.Thread(target=obj.add, args=(c,)) t.start() |