您的位置:首页 > 编程语言 > Python开发

python笔记六:进程与线程

2015-03-18 12:27 363 查看
1.进程

  1)调用unix/linux系统中的进程函数fork(),用法和linux相同,调用成功返回0,失败返回-1:

import os
print 'Process (%s) start...' % os.getpid()
pid = os.fork()
if pid==0:
print 'I am child process (%s) and my parent is %s.' % (os.getpid(), os.getppid())
else:
print 'I (%s) just created a child process (%s).' % (os.getpid(), pid)


  2)调用
multiprocessing模块:


  
multiprocessing
模块提供了一个
Process
类来代表一个进程对象,创建进程的过程:

  
Process()创建进程
实例,用
start()启动进程,join()等待进程处理。


from multiprocessing import Process
import os

def proc(name):
print 'child process %s (%s)...' % (name, os.getpid())

if __name__=='__main__':
print 'Parent process %s.' % os.getpid()
p = Process(target=proc, args=('test',))
print 'Process will start.'
p.start()
p.join()
print 'Process end.'


  3)创建进程池pool:

  对
Pool
对象调用
join()
方法会等待所有子进程执行完毕,调用
join()
之前必须先调用
close()
,调用
close()
之后就不能继续添加新的
Process
了。

from multiprocessing import Pool
import os, time, random

def long_time_task(name):
print 'Run task %s (%s)...' % (name, os.getpid())
start = time.time()
time.sleep(random.random() * 3)
end = time.time()
print 'Task %s runs %0.2f seconds.' % (name, (end - start))

if __name__=='__main__':
print 'Parent process %s.' % os.getpid()
p = Pool()
for i in range(5):
p.apply_async(long_time_task, args=(i,))
print 'Waiting for all subprocesses done...'
p.close()
p.join()
print 'All subprocesses done.'


  4)进程通信:pipes和queue.

2.线程

  线程在执行过程中与进程是有区别的。每个独立的线程有一个程序运行的入口、顺序执行序列和程序的出口。但是线程不能够独立执行,必须依存在应用程序中,由应用程序提供多个线程执行控制。
指令指针和堆栈指针寄存器是线程上下文中两个最重要的寄存器,线程总是在进程得到上下文中运行的,这些地址都用于标志拥有线程的进程地址空间中的内存。python中的两个线程模块thread
threading
thread
是低级模块,
threading
是高级模块,对
thread
进行了封装。

  1)函数式:调用thread模块中的start_new_thread()函数来产生新线程

  thread.start_new_thread ( function, args[, kwargs] )

import thread
import time

def print_time( threadName, delay):
count = 0
while count < 5:
time.sleep(delay)
count += 1
print "%s: %s" % ( threadName, time.ctime(time.time()) )

try:
thread.start_new_thread( print_time, ("Thread-1", 2, ) )
thread.start_new_thread( print_time, ("Thread-2", 4, ) )
except:
print "Error: unable to start thread"

while 1:
pass


  2)线程模块:

  threading.currentThread(): 返回当前的线程变量。

  threading.enumerate(): 返回一个包含正在运行的线程的list。正在运行指线程启动后、结束前,不包括启动前和终止后的线程。

  threading.activeCount(): 返回正在运行的线程数量,与len(threading.enumerate())有相同的结果。

  Thread类提供了以下方法:

  run(): 用以表示线程活动的方法。

  start():启动线程活动。

  join([time]): 等待至线程中止。这阻塞调用线程直至线程的join() 方法被调用中止-正常退出或者抛出未处理的异常-或者是可选的超时发生。

  isAlive(): 返回线程是否活动的。

  getName(): 返回线程名。

  setName(): 设置线程名。

import threading
import time

exitFlag = 0

class myThread (threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print "Starting " + self.name
print_time(self.name, self.counter, 5)
print "Exiting " + self.name

def print_time(threadName, delay, counter):
while counter:
if exitFlag:
thread.exit()
time.sleep(delay)
print "%s: %s" % (threadName, time.ctime(time.time()))
counter -= 1

thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)

thread1.start()
thread2.start()

print "Exiting Main Thread"


  3)
threading.Lock():锁只有一个,无论多少线程,同一时刻最多只有一个线程持有该锁.一个线程使用自己的局部变量比使用全局变量好,因为局部变量只有线程自己能看见,不会影响其他线程,而全局变量的修改必须加锁。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: