簡體   English   中英

如何在python的gevent中使用全局變量

[英]how to use global variable in python's 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 我知道gevent.spawn()函數,但是我不能像代碼中的results那樣執行獨占訪問共享變量。 我該怎么辦?

如果使用類似collections.deque之類的results類型,則可以避免使用鎖(可以安全地將deque對象中的值從不同的線程推入)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM