Home Python Python callback demo

Python callback demo

by zinan

import threading
import time

class TestThread(threading.Thread):
    def __init__(self,id,callback):
        threading.Thread.__init__(self)
        self.id = id
        self.callback = callback
        self.active = True

    def run(self):
        while self.active:
            self.callback(self.id)
            time.sleep(1)

class sessions:
    def __init__(self):
        self.thread = None
        self.str=”callback id:”

    def callback(self, id):
        print self.str,id

    def create_thread(self, id):
        self.thread=TestThread(id,self.callback)
        self.thread.start()

    def clean_thread(self):
        if self.thread:
            self.thread.active=False
            self.thread=None

if __name__ == ‘__main__’:
    sess=sessions()

    for i in range(100):
        sess.create_thread(i)
        time.sleep(1)
        sess.clean_thread()

打赏
0 comment

You may also like

Leave a Comment

*

code

error: Alert: Content is protected !!