Python Forum
How to do multithrading of a simple function?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to do multithrading of a simple function?
#1


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


Possibly Related Threads…
Thread Author Replies Views Last Post
  got SyntaxError while building simple function zarize 2 2,131 Feb-14-2020, 10:51 AM
Last Post: zarize
  Simple statistics with range function Pythonlearner2019 2 2,129 Nov-25-2019, 05:25 PM
Last Post: Pythonlearner2019
  Cannot get simple i/o to function. jerryi 10 6,728 Jul-27-2019, 06:22 PM
Last Post: jerryi
  Need help with a simple function WorldPark 4 2,662 Apr-26-2019, 12:28 PM
Last Post: perfringo
  Why this simple function doesnt work? blackknite 8 4,014 Jan-05-2019, 12:32 PM
Last Post: buran
  Simple Function Problem, please help ShadowWarrior17 16 7,082 Jan-03-2018, 09:29 PM
Last Post: ShadowWarrior17
  Simple Function Call PappaBear 2 3,175 Apr-04-2017, 11:12 PM
Last Post: PappaBear

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020