import queue
import threading
import time
from mycode.PythoncodeTool import PythoncodeTool


class PythonTManager:
    def __init__(self,maxnum):
        self.brun = True
        self.cur_num = 0
        self.put_lock = threading.Lock()
        # 构建进程池--Python 代码的执行在子进程完成-3个子进程
        self.maxnum = maxnum
        self.python_tool = PythoncodeTool(maxnum)   #python工具实例

    def __del__(self):
        self.shutdown_pool()

    def start_pool(self):
        return self.python_tool.start_pool()

    def shutdown_pool(self):
        self.python_tool.shutdown_pool()

    def is_pool_active(self):
        return self.python_tool.pool_active


    def execute_instruction(self,instruction):
        bwork = False
        while self.brun:
            with self.put_lock:
                if self.cur_num < self.maxnum:
                    self.cur_num += 1
                    bwork = True

            if bwork:#还有空的子进程
                #提交给进程池执行
                bsuccess,instruction,analysis,_,ext_params = self.python_tool.execute_instruction(instruction)
                #执行完成后,数量减一
                with self.put_lock:
                    self.cur_num -= 1
                #返回结果
                return bsuccess,instruction,analysis,analysis,ext_params
            else: #如果没获取的许可,则等待N秒后再尝试---存在问题:多线程间没有先来先到的机制了,有可能第一个来排队的一直等到最后
                time.sleep(20)  #休眠20秒