python 多线程内子线程结束后执行主线程
今天写case时发现一个场景,请求助力接口后需要统计被助力用户的助力次数
助力接口用线程并发的方式进行,代码如下
def test_case_08(self):
"""多用户并发助力"""
t1 = [threading.Thread(target=PreheatMethod().help, args=(i, self.A, 1)) for i in self.uid_list]
[i.start() for i in t1]
response = PreheatMethod().init(self.A)
print(f"当前用户被助力次数 :{response['data']['userInfo']['helpedCount']}次")
线程这里采用列表推导式进行uid列表循环制作线程
t1 = [threading.Thread(target=PreheatMethod().help, args=(i, self.A, 1)) for i in self.uid_list]
发现的问题就是,子线程进行第一个线程i.start()时就会直接执行下面的PreheatMethod().init(self.A)方法这样就没发起到统计的作用了
解决方法:添加[j.join() for j in t1]进行子线程阻塞
def test_case_08(self):
"""多用户并发助力"""
t1 = [threading.Thread(target=PreheatMethod().help, args=(i, self.A, 1)) for i in self.uid_list]
[i.start() for i in t1]
[j.join() for j in t1]
response = PreheatMethod().init(self.A)
print(f"当前用户被助力次数 :{response['data']['userInfo']['helpedCount']}次")
主程序将一直等待子程序全部运行完成才结束