python中对象方法的多线程处理



我正在尝试用oops-实现多线程


class test:
def printer(self):
for ctr in range(1000000):
print("hello")
def printHi(self):
for ctr in range(1000000):
print("hi")

if __name__ == "__main__":
test1 = test()
t1 = threading.Thread(target=test1.printHi, args=(10,))
t2 = threading.Thread(target=test1.printer, args=(10,))
t1.start()
t2.start()
print("Done!")

但是测试1.printHi希望我能通过自我

Exception in thread Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python3.9/threading.py", line 973, in _bootstrap_inner
Thread-2:
Traceback (most recent call last):
File "/usr/lib/python3.9/threading.py", line 973, in _bootstrap_inner
self.run()
File "/usr/lib/python3.9/threading.py", line 910, in run
self.run()
File "/usr/lib/python3.9/threading.py", line 910, in run
self._target(*self._args, **self._kwargs)    self._target(*self._args, **self._kwargs)
TypeError: printHi() takes 1 positional argument but 2 were givenTypeError: 
printer() takes 1 positional argument but 2 were given
Done!

通过自检后,它不再是多线程的it

t1 = threading.Thread(target=test1.printHi())
t2 = threading.Thread(target=test1.printer())
t1.start()
print("next")
t2.start()

它首先打印所有的hi,然后最后打印hello,接下来就是打印,但当我像实现函数一样实现它们时,它们会正常工作,它们会立即组合打印。正确实现它的方法是什么,以便两个线程同时运行。。。

您似乎在向方法传递额外的10;尝试:


class test:
def printer(self):
for ctr in range(10):
print("hello")
time.sleep(1)
def printHi(self):
for ctr in range(10):
print("hi")
time.sleep(1)

if __name__ == "__main__":
test1 = test()
t1 = threading.Thread(target=test1.printHi, args=())
t2 = threading.Thread(target=test1.printer, args=())
t1.start()
t2.start()
print("Done!")

或者,如果你想保留参数,函数需要接受它:


class test:
def printer(self, n):
for ctr in range(10):
print("hello", n)
time.sleep(1)
def printHi(self, n):
for ctr in range(10):
print("hi", n)
time.sleep(1)

if __name__ == "__main__":
test1 = test()
t1 = threading.Thread(target=test1.printHi, args=(10,))
t2 = threading.Thread(target=test1.printer, args=(10,))
t1.start()
t2.start()
print("Done!")

相关内容

  • 没有找到相关文章

最新更新