python - module - mythread

本文介绍了一个基于Python的自定义线程管理方案,通过创建myThread子类来实现线程的启动、暂停、恢复和停止等功能。同时,还提供了一个线程参数管理类myThreadParam,用于线程运行条件的配置及状态监测。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

python  module - mythread


'''
threading.Thread subclass mythread

from mythread import myThread
from mythread import setlogger
from mythread import myThreadParam as myParam
from mythread import T
from mythread import Sparam

def condfunc(mp):
    return not mp.condparam 

def func(mp):
    param = mp.param
    a = param.a0
    b = param.a1
    c = param.a2
    debug(T(mp) + param.name)

def main():
...
    param = Sparam('tname') # struct param
    param.set(a, b, c, d)
    mp = myParam(param, False, condfunc) # new thread param
    
    try:
        t = myThread(tname, func, mp)  #Create and Start a thread
        t.start()
    except:
        error('error in myThread')

    #stop the thread
    mp.condparam = True
    t.stop()


'''

import threading
import time
import sys
#from mylog import logger as log


class Sparam:
    def __init__(self, name):
        self.name = name
        self.a0 = None
        self.a1 = None
        self.a2 = None
        self.a3 = None
        
    def set(self, a0,a1 = None,a2 = None,a3 = None):
        self.a0 = a0
        self.a1 = a1
        self.a2 = a2
        self.a3 = a3


class myThreadParam():
    param = None
    pid = None
    pname = None
    def __init__(self, param, condparam = None, condfunc = None):
        self.param = param # param
        self.condfunc = condfunc # cond func
        self.condparam = condparam # init cond
    def setpid(self, pid):
        self.pid = pid
    def setpname(self, pname):
        self.pname = pname
    def isRunning(self):
        if self.condfunc is None:
            debug('isRunning : condfunc is None')
            return True
        else :
            return self.condfunc(self)
    
logger = None
    
def setlogger(mylog):
    global logger
    logger = mylog

def debug(msg):
    global logger
    if logger is not None:
        logger.debug(msg)

def T(mp):
    if mp is None: return ''
    tag = '(' + str(mp.pid) + ')' + mp.pname + ': '
    return tag

class myThread(threading.Thread):
    def __init__(self, name, func, param):
        debug('Create thread -- ' + name)
        threading.Thread.__init__(self)
        #self.threadID = threadID
        self.name = name
        self.param = param
        self.func = func
        self.__flag = threading.Event()
        self.__flag.set()
        self.__running = threading.Event()
        self.__running.set()
    
    def run(self):
        self.param.setpid(self.ident)
        self.param.setpname(self.name)
        start = time.time()
        debug( "Starting " + self.name + ' at ' + str(start))
        while self.__running.isSet() and self.param.isRunning():
            self.func(self.param)
            #self.__flag.wait(0.5)
        debug( "Exiting " + self.name + ' start at ' + str(start) + ' exit ' + str(time.time()))
    
    def pause(self):
        self.__flag.clear()
        
    def resume(self):
        self.__flag.set()
        
    def stop(self, timeout = None):
        self.__flag.set()
        self.__running.clear()
        debug('mythread: stop ')
        for i in range(10):
            try:
                self.join(timeout)
            except:
                debug(sys.exc_info())
                continue
            break
    
    

	
	

### Python 中进程与线程的概念 #### 进程 (Process) 进程是指操作系统结构中的基本单元,拥有独立的地址空间。每个进程都有自己私有的数据段、堆栈区和全局变量等资源,在创建子进程时会复制父进程的数据副本[^3]。 - **优点** - 更高的稳定性:由于各进程间相互隔离,一个进程崩溃不会影响其他进程。 - **缺点** - 创建销毁成本高:因为涉及内存分配等问题,所以开销较大。 - 数据共享困难:不同进程之间传递消息较为复杂。 ```python from multiprocessing import Process, Queue def f(q): q.put([42, None, 'hello']) if __name__ == '__main__': queue = Queue() p = Process(target=f, args=(queue,)) p.start() print(queue.get()) # prints "[42, None, 'hello']" p.join() ``` #### 线程 (Thread) 线程是进程中可调度运行的一个实体;同一进程下的多个线程共享该进程的所有资源,包括代码段、数据段等,但每个线程有自己的调用栈[^1]。 - **优点** - 启动速度快:相比于进程来说更轻量级。 - 资源消耗少:不需要像启动新进程那样占用大量系统资源。 - **缺点** - 容易受到GIL(Global Interpreter Lock)的影响,在CPU密集型任务上表现不佳。 - 如果某个线程发生异常,则可能会影响到整个程序的安全性和可靠性。 ```python import threading class MyThread(threading.Thread): def run(self): print(f"{threading.current_thread().getName()} started") threads = [] for i in range(5): t = MyThread() threads.append(t) t.start() for thread in threads: thread.join() print("All threads finished execution.") ``` ### 应用场景分析 对于I/O 密集型操作(如文件读写、网络请求),推荐使用多线程来处理,这样可以在等待期间让出 CPU 给其他线程继续工作,从而提高整体性能。 而对于计算密集型的任务(比如大规模数据分析或图像渲染),则更适合采用多进程方案,以充分利用多核处理器的优势并绕过 GIL 的限制。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值