Chinaunix首页 | 论坛 | 博客
  • 博客访问: 282376
  • 博文数量: 40
  • 博客积分: 1807
  • 博客等级: 上尉
  • 技术积分: 350
  • 用 户 组: 普通用户
  • 注册时间: 2009-08-03 15:42
文章分类

全部博文(40)

文章存档

2011年(18)

2010年(20)

2009年(2)

我的朋友

分类: LINUX

2010-11-09 20:45:59

   粗鲁的将一个线程关闭是不可取的,因为该线程可能正在访问一些需要主动关闭的资源或者该线程还产生了另外一些需要关闭的线程。因此Python threading并没有提供线程关闭的API。
   为了程序的需要,我们可能确实需要主动关闭一些线程,有两种方法可以work around:
  • 一种是用python multiprocessing的多进程来代替多线程,multiprocessing提供了关闭进程的接口terminate。

import time
    from processing import Process
    class test():

       def f(self, name):
          ctr = 0
          while 1:
              ctr += 1
              print ' hello', name, ctr
              time.sleep(0.5)
       

    if __name__ == '__main__':
          CT=test()
          p = Process(target=CT.f, args=('P',))
          p.start()

          key = raw_input("Press ")
          p.terminate() ## p2 terminated here


  • 第二种方法是使用flag变量:

import threading
    import time

    class TestThread(threading.Thread):
        def __init__(self):
            threading.Thread.__init__(self)
            self.running = True
            self.times = 0
           
        def run(self):
            #note: we don't set self.running to False anywhere...
            while self.running:
                self.times += 1
                print self.times
                time.sleep(.05)

    if __name__ == '
__main__':
        # create the thread
        thread = TestThread()
        # start it up
        thread.start()
        raw_input("Hit ")
        # don'
t continue the while loop anymore
        thread.running = False
        # wait for the thread to finish what it's doing

        thread.join()


阅读(3477) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~