import thread

来源:互联网 发布:数据审核制度 编辑:程序博客网 时间:2024/04/29 17:53

线程:子进程,多个子线程运行在同一个进程中,共享运行环境

start_new_thread(function, args)

产生新的线程运行function

再threading.Thread(target=fun, args=())

作用产生一个线程对象

进程与线程

子进程和父进程有不同的代码和数据空间,而多个线程则共享数据空间,每个线程有自己的执行堆栈和程序计数器其执行上下文。

多线程主要是为了节约CPU时间,发挥利用,根据具体情况而定。线程的运行中需要使用计算机的内存资源和CPU。 

线程的划分

主线程(主程序)

线程(子线程)

关系:

主线程负责子线程的作业调度

数据的提供,接收

import threadimport timedef t(n,lock1):    print '22222'    time.sleep(n)    print 'ddddd'    lock1.release()lock1=thread.allocate_lock()lock1.acquire()thread.start_new_thread(t,(4,lock1))while lock1.locked():passprint 'sssss'  

import threadimport timedef t(n,lock1):    print '22222'    time.sleep(n)    print 'ddddd'    lock1.release()def th(n,lock2):    print '22222'    time.sleep(n)    print 'ddddd'    lock2.release()lock1=thread.allocate_lock()lock1.acquire()thread.start_new_thread(t,(4,lock1))lock2=thread.allocate_lock()lock2.acquire()thread.start_new_thread(t,(4,lock2))while lock1.locked():passwhile lock2.locked():passprint 'sssss'