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():鎖只有一個,不管多少線程,同一時刻最多隻有一個線程持有該鎖.一個線程使用本身的局部變量比使用全局變量好,由於局部變量只有線程本身能看見,不會影響其餘線程,而全局變量的修改必須加鎖。

相關文章
相關標籤/搜索