python笔记六:进程与线程

1.进程python

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

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模块:app

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

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

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了。spa

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.线程unix

  线程在执行过程当中与进程是有区别的。每一个独立的线程有一个程序运行的入口、顺序执行序列和程序的出口。可是线程不可以独立执行,必须依存在应用程序中,由应用程序提供多个线程执行控制。指令指针和堆栈指针寄存器是线程上下文中两个最重要的寄存器,线程老是在进程获得上下文中运行的,这些地址都用于标志拥有线程的进程地址空间中的内存。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():锁只有一个,不管多少线程,同一时刻最多只有一个线程持有该锁.一个线程使用本身的局部变量比使用全局变量好,由于局部变量只有线程本身能看见,不会影响其余线程,而全局变量的修改必须加锁。

相关文章
相关标签/搜索