|
10鱼币
本帖最后由 wgij007 于 2023-7-28 08:09 编辑
import wmi
import threading # 多线程
import time
c = wmi.WMI()
lock = threading.Lock()
def sn_test():
##lock.acquire()
print (11)
i = 0
while i < 2:
print (22)
for physical_disk in c.Win32_DiskDrive():
print (33)
sn = physical_disk.SerialNumber.strip()
print (sn)
time.sleep(0.2) # 刷新速度
i += 1
##timeout = 0.5
def thread01():
thread01_a = threading.Thread(name = 'python_thread01', target = sn_test)
thread01_a.setDaemon(True)
thread01_a.start() # 线程开始
if __name__ == '__main__':
thread01()
直接运行 sn_test() 正常没问题
11
22
33
3035323042363737323835393130463320202020
33
4141303030303030303030303030303038303333
22
33
3035323042363737323835393130463320202020
33
4141303030303030303030303030303038303333
输出结束,返回值是[0].
但经过thread01()
11
22
输出结束,返回值是[0].
,就只到22那,就终止了。如果不锁就会出错,不知为什么,求解
很玄学的问题,我也不知道为什么
- import threading # 多线程
- import time
- lock = threading.Lock()
- def sn_test():
- import wmi
- c = wmi.WMI()
- # lock.acquire()
- print(11)
- i = 0
- while i < 2:
- print(22)
- for physical_disk in c.Win32_DiskDrive():
- print(33)
- sn = physical_disk.SerialNumber.strip()
- print(sn)
- time.sleep(0.2) # 刷新速度
- i += 1
- # timeout = 0.5
- def thread01():
- thread01_a = threading.Thread(name='python_thread01', target=sn_test)
- thread01_a.setDaemon(True)
- thread01_a.start() # 线程开始
- thread01_a.join()
- if __name__ == '__main__':
- thread01()
复制代码
setDaemon会把线程变为守护线程,主线程不会等待守护线程完成后再结束,它会强制结束,所以加个.join()保证线程的执行
我在我这里测试后发现会报错“发生意外”,把import wmi和c = wmi.WMI()移到子线程后就不报错了
|
最佳答案
查看完整内容
很玄学的问题,我也不知道为什么
setDaemon会把线程变为守护线程,主线程不会等待守护线程完成后再结束,它会强制结束,所以加个.join()保证线程的执行
我在我这里测试后发现会报错“发生意外”,把import wmi和c = wmi.WMI()移到子线程后就不报错了
|