码迷,mamicode.com
首页 > 编程语言 > 详细

python笔记六:进程与线程

时间:2015-03-18 13:42:59      阅读:227      评论:0      收藏:0      [点我收藏+]

标签:

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中的两个线程模块threadthreadingthread是低级模块,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():锁只有一个,无论多少线程,同一时刻最多只有一个线程持有该锁.一个线程使用自己的局部变量比使用全局变量好,因为局部变量只有线程自己能看见,不会影响其他线程,而全局变量的修改必须加锁。

python笔记六:进程与线程

标签:

原文地址:http://www.cnblogs.com/xp12/p/4346840.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!