python的thearding在执行并行的时候有几个误区需要注意,刚开始接触python所有有些无耐,特此记录,希望能对像我一样的小白有一点小小的作用
正文:
误区一:threading.Thread中target参数对应函数直接调用方法
错误代码
#!/usr/bin/env python3
import threading
def out_name(name):
for i in range(5):
print(name, ":", i)
def thread_test():
tone = threading.Thread(target=out_name("123"))
print("this first")
ttwo = threading.Thread(target=out_name("456"))
ttwo.start()
tone.start()
if __name__ == "__main__":
thread_test()
输出结果:
stb_py\process>theard.py
123 : 0
123 : 1
123 : 2
123 : 3
123 : 4
this first
456 : 0
456 : 1
456 : 2
456 : 3
这里并不是并行作用,而是因为你直接调用了out_name方法,所以还是串行直接调用函数的关系
误区二:arge参数中直接赋值,导致参数数目不对
错误代码
#!/usr/bin/env python3
import threading
def out_name(name):
for i in range(5):
print(name, ":", i)
def thread_test():
tone = threading.Thread(target=out_name, args="123")
print("this first")
ttwo = threading.Thread(target=out_name, args="456")
ttwo.start()
tone.start()
if __name__ == "__main__":
thread_test()
输出:
stb_py\process>theard.py
this first
Exception in thread Thread-2:
Traceback (most recent call last):
File "E:\python\lib\threading.py", line 932, in _bootstrap_inner
Exception in thread Thread-1:
Traceback (most recent call last):
File "E:\python\lib\threading.py", line 932, in _bootstrap_inner
self.run()
File "E:\python\lib\threading.py", line 870, in run
self.run()
File "E:\python\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
TypeError: out_name() takes 1 positional argument but 3 were given
self._target(*self._args, **self._kwargs)
TypeError: out_name() takes 1 positional argument but 3 were given
正确调用方式:
参数使用元组,这样代表了一个参数,如果像二中示例那样,参数会默认为传入多个字符,导致参数数目不一致的问题。
#!/usr/bin/env python3
import threading
def out_name(name):
for i in range(5):
print(name, ":", i)
def thread_test():
tone = threading.Thread(target=out_name, args=("123",))
print("this first")
ttwo = threading.Thread(target=out_name, args=("456",))
ttwo.start()
tone.start()
if __name__ == "__main__":
thread_test()
输出结果:
stb_py\process>theard.py
this first
456 : 0
456 : 1
456 : 2
456 : 3
456 : 4
123 : 0
123 : 1
123 : 2
123 : 3
123 : 4









网友评论