qq_46601351 2022-06-16 15:11 采纳率: 50%
浏览 89
已结题

python多线程执行测试用例

1 下列有一个简单的任务,每个任务都会睡眠10秒,如果是用单线程运行,至少要运行100秒,请使用多线程启动10个线程运行,实现10秒左右运行完所有任务

任务代码:

import unittest,threading
def test_task(name):
    print(f"{threading.current_thread().name}:",name)
    time.sleep(10)

class TestTask(unittest.TestCase):
    def test01(self):
        test_task(1)
    def test02(self):
        test_task(2)
    def test03(self):
        test_task(3)
    def test04(self):
        test_task(4)
    def test05(self):
        test_task(5)
    def test06(self):
        test_task(6)
    def test07(self):
        test_task(7)
    def test08(self):
        test_task(8)
    def test09(self):
        test_task(9)
    def test10(self):
        test_task(10)
  • 写回答

3条回答 默认 最新

  • 懒羊羊的南瓜屋 2022-06-16 16:46
    关注
    
    import unittest,threading
    
    import time
    
    
    def test_task(name):
        print("thread:{} start".format(name))
        time.sleep(10)
        print("thread:{} finish".format(name))
    
    class TestTask(unittest.TestCase):
        def __init__(self):
            self.fun=[self.test01,self.test02,self.test03,self.test04,self.test05,
                      self.test06,self.test07,self.test08,self.test09,self.test10]
    
        def test01(self):
            test_task(1)
    
        def test02(self):
            test_task(2)
    
        def test03(self):
            test_task(3)
    
        def test04(self):
            test_task(4)
    
        def test05(self):
            test_task(5)
    
        def test06(self):
            test_task(6)
    
        def test07(self):
            test_task(7)
    
        def test08(self):
            test_task(8)
    
        def test09(self):
            test_task(9)
    
        def test10(self):
            test_task(10)
    
    if __name__ == "__main__":
        testcases = TestTask()
        for i in range(10):
            case_thread = threading.Thread(target=testcases.fun[i])
            case_thread.daemon = True
            case_thread.start()
        #wait all finish
        time.sleep(2000)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 6月26日
  • 已采纳回答 6月18日
  • 创建了问题 6月16日

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办