I am trying to implement multi threading with oops
JavaScript
x
18
18
1
class test:
2
def printer(self):
3
for ctr in range(1000000):
4
print("hello")
5
6
def printHi(self):
7
for ctr in range(1000000):
8
print("hi")
9
10
if __name__ == "__main__":
11
test1 = test()
12
13
t1 = threading.Thread(target=test1.printHi, args=(10,))
14
t2 = threading.Thread(target=test1.printer, args=(10,))
15
t1.start()
16
t2.start()
17
print("Done!")
18
But the test1.printHi is expecting me to pass self
JavaScript
1
16
16
1
Exception in thread Exception in thread Thread-1:
2
Traceback (most recent call last):
3
File "/usr/lib/python3.9/threading.py", line 973, in _bootstrap_inner
4
Thread-2:
5
Traceback (most recent call last):
6
File "/usr/lib/python3.9/threading.py", line 973, in _bootstrap_inner
7
self.run()
8
File "/usr/lib/python3.9/threading.py", line 910, in run
9
self.run()
10
File "/usr/lib/python3.9/threading.py", line 910, in run
11
self._target(*self._args, **self._kwargs) self._target(*self._args, **self._kwargs)
12
13
TypeError: printHi() takes 1 positional argument but 2 were givenTypeError:
14
printer() takes 1 positional argument but 2 were given
15
Done!
16
After passing self it is not being multi threaded any more It
JavaScript
1
6
1
t1 = threading.Thread(target=test1.printHi())
2
t2 = threading.Thread(target=test1.printer())
3
t1.start()
4
print("next")
5
t2.start()
6
Its first printing all hi and then hello at last next is getting printed but when I implement them like functions its working properly they are getting printed at once combined. Whats the right way to implement it properly such that both threads runs simultaneously…
Advertisement
Answer
You seem to be passing an extra 10 to the methods; try:
JavaScript
1
20
20
1
class test:
2
def printer(self):
3
for ctr in range(10):
4
print("hello")
5
time.sleep(1)
6
7
def printHi(self):
8
for ctr in range(10):
9
print("hi")
10
time.sleep(1)
11
12
if __name__ == "__main__":
13
test1 = test()
14
15
t1 = threading.Thread(target=test1.printHi, args=())
16
t2 = threading.Thread(target=test1.printer, args=())
17
t1.start()
18
t2.start()
19
print("Done!")
20
Or, if you want to keep the parameter, the functions need to accept it:
JavaScript
1
20
20
1
class test:
2
def printer(self, n):
3
for ctr in range(10):
4
print("hello", n)
5
time.sleep(1)
6
7
def printHi(self, n):
8
for ctr in range(10):
9
print("hi", n)
10
time.sleep(1)
11
12
if __name__ == "__main__":
13
test1 = test()
14
15
t1 = threading.Thread(target=test1.printHi, args=(10,))
16
t2 = threading.Thread(target=test1.printer, args=(10,))
17
t1.start()
18
t2.start()
19
print("Done!")
20