Python Forum

Full Version: How to do multithrading of a simple function?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.


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())
#!/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()