python多线程编程

python多线程

传入函数创建线程

#!/usr/bin/python

import os
import sys
import time
import signal
import threading

def timer(no, interval):
    cnt = 0
    while cnt<10:
        print 'Thread:(%d) Time:%s/n'%(no, time.ctime())
        time.sleep(interval)
        cnt += 1

if __name__ == '__main__':
    #Initialize a thread object, passing in the function timer, and its parameters
    th1 = threading.Thread(target=timer, args=(1,1));
    th2 = threading.Thread(target=timer, args=(2,2));

    #Start thread
    th1.start()
    th2.start()

    #Main thread waits until child threads exit,without threading.join(),the main thread will exit even the child
    #threads is still running
    th1.join()
    th2.join()
    print "main thread exit..."

继承类创建线程

#!/usr/bin/python

import os
import sys
import threading
import signal
import time

class timer(threading.Thread): #The timer class is derived from the class threading.Thread
    def __init__(self, num, interval):
        threading.Thread.__init__(self)
        self.thread_num = num
        self.interval = interval
        self.thread_stop = False

    def run(self): #Overwrite run() method, put what you want the thread do here
        while not self.thread_stop:
            print 'Thread Object(%d), Time:%s' %(self.thread_num, time.ctime())
            time.sleep(self.interval)
            
    def stop(self):
        self.thread_stop = True

if __name__ == '__main__':
    Watcher()
    thread1 = timer(1, 1)
    thread2 = timer(2, 2)
    thread1.start()
    thread2.start()
    thread1.join()
    thread2.join()
    print "main thread exit..."

上面的程序在会出现无法响应ctrl + C 的情况,导致程序无法退出,可以加入一个Watcher的监控进程,来捕捉 ctrl + c的信号, 只需把Watcher()在线程创建之前调用即可.

class Watcher:
    def __init__(self):
        """ Creates a child thread, which returns.  The parent
            thread waits for a KeyboardInterrupt and then kills
            the child thread.
        """
        self.child = os.fork()
        if self.child == 0:
            return
        else:
            self.watch()

    def watch(self):
        try:
            os.wait()
        except KeyboardInterrupt:
            print ' exit...'
            self.kill()
        sys.exit()

    def kill(self):
        try:
            os.kill(self.child, signal.SIGKILL)
        except OSError:
            pass

python多线程有个限制,全局解释器锁(global interpreter lock),这个锁的意思是任一时间只能有一个线程使用解释器,跟单cpu跑多个程序一个意思,大家都是轮着用的,这叫“并发”,不是“并行”。手册上的解释是为了保证对象模型的正确性!这个锁造成的困扰是如果有一个计算密集型的线程占着cpu,其他的线程都得等着....,试想你的多个线程中有这么一个线程,得多悲剧,多线程生生被搞成串行;当然这个模块也不是毫无用处,手册上又说了:当用于IO密集型任务时,IO期间线程会释放解释器,这样别的线程就有机会使用解释器了!所以是否使用这个模块需要考虑面对的任务类型。

标签:Python

评论已关闭