2013-04-02 39 views
0

我目前正在研究一個程序,其中多個線程需要訪問單個數組列表。該數組充當「緩衝區」。一個或多個線程寫入此列表,一個或多個其他線程讀取並從此列表中刪除。我的第一個問題是,Python中的數組是否線程安全?如果不是,處理情況的標準方法是什麼?多線程需要訪問單個資源

回答

1

您應該使用queue庫。 here是一篇很好的關於線程和隊列的文章。

import Queue 
import threading 
import urllib2 
import time 
from BeautifulSoup import BeautifulSoup 

hosts = ["http://yahoo.com", "http://google.com", "http://amazon.com", 
     "http://ibm.com", "http://apple.com"] 

queue = Queue.Queue() 
out_queue = Queue.Queue() 

class ThreadUrl(threading.Thread): 
    """Threaded Url Grab""" 
    def __init__(self, queue, out_queue): 
     threading.Thread.__init__(self) 
     self.queue = queue 
     self.out_queue = out_queue 

    def run(self): 
     while True: 
      #grabs host from queue 
      host = self.queue.get() 

      #grabs urls of hosts and then grabs chunk of webpage 
      url = urllib2.urlopen(host) 
      chunk = url.read() 

      #place chunk into out queue 
      self.out_queue.put(chunk) 

      #signals to queue job is done 
      self.queue.task_done() 

class DatamineThread(threading.Thread): 
    """Threaded Url Grab""" 
    def __init__(self, out_queue): 
     threading.Thread.__init__(self) 
     self.out_queue = out_queue 

    def run(self): 
     while True: 
      #grabs host from queue 
      chunk = self.out_queue.get() 

      #parse the chunk 
      soup = BeautifulSoup(chunk) 
      print soup.findAll(['title']) 

      #signals to queue job is done 
      self.out_queue.task_done() 

start = time.time() 
def main(): 

    #spawn a pool of threads, and pass them queue instance 
    for i in range(5): 
     t = ThreadUrl(queue, out_queue) 
     t.setDaemon(True) 
     t.start() 

    #populate queue with data 
    for host in hosts: 
     queue.put(host) 

    for i in range(5): 
     dt = DatamineThread(out_queue) 
     dt.setDaemon(True) 
     dt.start() 


    #wait on the queue until everything has been processed 
    queue.join() 
    out_queue.join() 

main() 
print "Elapsed Time: %s" % (time.time() - start) 
0

您需要像ATOzTOA提到的鎖。您通過創建它們

lock = threading.Lock() 

並且線程在它們進入關鍵部分時獲取它們。完成該部分後,他們解鎖。 pythonic的寫法是

with lock: 
    do_something(buffer)