线程:操作系统能够进行运算调度的最小单位。它被包含在进程之中,是进程中的实际运作单位。一条线程指的是进程中一个单一顺序的控制流,一个进程可以并发多个线程,每条线程并行执行不同的任务。
进程:以一个整体的形式暴露给操作系统管理,里面包含对各个资源的调用,内存的管理,网络接口的调用等,对各种资源管理的集合。
进程与线程的区别:
1、线程共享内存空间,进程的内存是独立的;
2、同一个进程的线程之间可以直接交流,两个进程想通信,必须通过中间代理来实现;
3、创建新线程很简单,创建新进程需要对其父进程进行一次克隆;
4、一个线程可以控制和操作同一进程里的其它线程,但是进程只能操作子进程。
CPU 工厂
进程 车间(工厂的电力有限,一次只能给一个车间使用:单个CPU一次只能运行一个任务)
线程 工人(一个车间里有很多工人:一个进程里可以有很多线程)
threading.current_thread() 返回当前线程
threading.active_count() 返回当前活动线程的个数
在线程start()之前,用线程的setDaemon方法(实参为True),可以将该线程设为守护线程,主线程执行完毕不会等守护线程是否执行完毕(应用场景:SocketServer每一个连接都是子线程,关闭SocketServer的时候不希望等待子线程的结束)。
多线程的基本使用
""" 方法一 """ def say(word, second): print word time.sleep(second) t1 = threading.Thread(target=say, args=("I'm t1!", 2)) t2 = threading.Thread(target=say, args=("I'm t2!", 6)) """ 方法二 """ class MyThread(threading.Thread): def __init__(self, word, second): super(MyThread, self).__init__() self.word = word self.second = second def run(self): print self.word time.sleep(self.second) t1 = MyThread("I'm t1!", 2) t2 = MyThread("I'm t2!", 6) t1.start() t2.start()
计算所有子线程总共运行的时间
class MyThread(threading.Thread): def __init__(self, word, second): super(MyThread, self).__init__() self.word = word self.second = second def run(self): print self.word time.sleep(self.second) thread_list = [] begin_time = time.time() for i in range(10): t = MyThread("I'm t%s" % i, i) t.start() thread_list.append(t) for thread in thread_list: thread.join() # 等待线程执行结束 print '所有线程总共运行{}秒'.format(time.time() - begin_time) I'm t0 I'm t1 I'm t2 I'm t3 I'm t4 I'm t5 I'm t6 I'm t7 I'm t8 I'm t9 所有线程总共运行9.01185703278秒