Pyforms(1) 模拟进程互斥机制

环境:Python 3.6.3 + Pyforms 3.0.0

模拟:不同线程对同一块内存的读写互斥

 

import threading as td
import pyforms
from pyforms import BaseWidget
from pyforms.controls import ControlText
from pyforms.controls import ControlButton
import time

# 读线程即为处理线程/cpu线程
# 写线程即为添加作业到作业池

class mt(BaseWidget):
    def __init__(self):
        # GUI
        super(mt, self).__init__('moreThread')
        self._cpu = ControlText('当前读取数据')
        self._app = ControlText('准备写入数据')
        self._liv = ControlText('实时信息显示')
        self._button = ControlButton('Press')
        self._button.value = self.pre
        self.set_margin(20)

        # 作业编号
        self.number = 0
        # 作业池
        self.process = []
        # 处理器
        self.cpu = 1
        # 处理器锁
        self.lock_cpu = 1
        # 作业锁
        self.lock_pro = 1
        # 作业数
        self.count = 0
        # 多线程
        cpu_thread = td.Thread(target=self.work)
        cpu_thread.start()
        self.app_thread = td.Thread(target=self.app)

    # 处理作业
    def work(self):
        while True:
            # 等待cpu空闲
            while self.lock_cpu == 0:
                pass
            # 等待作业
            while self.count == 0:
                pass
            # 等待作业锁
            while self.lock_pro == 0:
                pass
            # 作业池上锁
            self.lock_pro = 0
            # 获取作业池信息
            number = self.process[0]
            self._cpu.value = str(number)
            self.process = self.process[1:]
            # 作业锁解锁
            self.lock_pro = 1
            # cpu上锁
            self.lock_cpu = 0
            # cpu处理作业
            time.sleep(3)
            self.count -= 1
            self._liv.value = (str(number)+'号作业运行')
            # cpu解锁
            self.lock_cpu = 1

    # 添加作业池
    def append(self):
        # 等待作业锁
        while self.lock_pro == 0:
            pass
        # 作业锁上锁
        self.lock_pro = 0
        # 添加作业池
        self.number += 1
        # 作业池添加中
        time.sleep(1)
        self._app.value = str(self.number)
        if len(self.process) < 10:
            self.count += 1
            self.process.append(self.number)
            self._liv.value = (str(self.number)+'号作业进入作业池')
        else:
            print(str(self.number)+'号作业添加失败')
        # 作业锁解锁
        self.lock_pro = 1

    def pre(self):
        self.app_thread.start()

    def app(self):
        while True:
            self.append()
            time.sleep(1)


pyforms.start_app(mt)

 

阅读更多
个人分类: Python
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭