2015-11-28 50 views
1

我是新來的python的gevent。我可以實現多線程邏輯如下:如何在python的gevent中使用全局變量

results = [] 
lock = threading.Lock() 
threads = [] 

def fetch(page_num): 
    data = get_some_data_from_url(page_num) 

    lock.acquire() 
    results.append(data) 
    lock.release() 

for i in range(1, 10): 
    thread = threading.Thread(target=fetch, args=(i,)) 
    thread.start() 
    threads.append(thread) 

for thread in threads: 
    thread.join() 

如何做到這一點使用gevent?我已經知道gevent.spawn()函數,但我不能這樣做獨佔訪問共享變量如results在代碼中。何我做?

回答

0

你能避免鎖,如果你使用類似collections.dequeresults類型(你可以從不同的線程安全的一個deque對象推值)