![](/img/trans.png)
[英]Running several python scripts in endless loops and in parallel (with PowerShell)
[英]Running two endless parallel loops
我想運行兩個無盡的並行循環。 一種是從服務器讀取數據並用數字更新對象。 另一個是什么也不做,然后讀取它,如果有更改,則對其進行處理。 不必保持同步。 所以我的問題是:
任何幫助表示贊賞。
簡短的答案是,您認為可以理解的任何內容。 意思是,出於學習目的,您的代碼應該對您有意義。
這是一個例子,它輕巧易用。 從線程獲取值和向線程獲取值很容易。這不是實際的多線程(同一CPU內核)
from threading import *
class worker(Thread):
def __init__(self, input=0):
self.input = input
Thread.__init__(self)
self.start()
def run(self):
while 1:
self.input += 1
x = worker(-100)
y = worker(x.input)
print y.input
這只是一個示例,說明Y
線程可以訪問x
的數據。實際上,考慮到兩個線程都將更新同一變量,這可能很危險:)(簡而言之:-100將在每個循環中兩次被計算, -98,-96,-94 ..等)
from threading import Thread
from Queue import Queue
class producer(Thread):
def __init__(self,queue):
Thread.__init__(self)
self.queue=queue
self.start()
def run(self):
while 1:
self.queue.put(update_value())
class consumer(Thread):
def __init__(self,queue):
Thread.__init__(self)
self.queue=queue
self.start()
def run(self):
while True:
value = queue.get()
do_whatever_you_want(value)
queue = Queue()
producer(queue)
consumer(queue)
請注意,您可以通過使用100個生產者和一個消費者(當然還有一個隊列)進行擴展,應該可以使用100個線程,但是如果您想使用10000,則情況會有所不同
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.