2017-09-13 69 views
0

我从API获取两个数据流,所以有三个线程,main,stream1和stream2。 Stream1和Stream2需要处理这些数据,一旦完成,它们将存储在main_value1和main_value2上。在多线程中读取一个变量

从主线程我需要读取任何给定时间的最后一个值(所以如果我需要这个值,它仍然处理,然后我得到最后处理/存储一个),什么是最佳的方式?从这里的代码示例中,我需要帮助编码功能get_main_value1(),当然,get_main_value2()

def stream1(): 
    while True: 
     main_value1 = process() 
def stream2(): 
    while True: 
     main_value2 = process2() 
def get_main_value1(): ? 
def get main_value2(): ? 
def main(): 
    threading.Thread(function=stream1,).start() 
    threading.Thread(function=stream2).start() 
    while True: 
     time.sleep(random.randint(0,10)) 
     A = get_main_value1() 
     B = get_main_value2() 

回答

0

一个办法是让他们全球:

STREAM1_LAST_VALUE = None 
def stream1(): 
    global STREAM1_LAST_VALUE 
    while True: 
     main_value1 = process() 
     STREAM1_LAST_VALUE = main_value1 

STREAM2_LAST_VALUE = None 
def stream2(): 
    global STREAM2_LAST_VALUE 
    while True: 
     main_value2 = process2() 
     STREAM2_LAST_VALUE = main_value2 

def get_main_value1(): 
    return STREAM1_LAST_VALUE 

def get main_value2(): 
    return STREAM2_LAST_VALUE 

def main(): 
    threading.Thread(function=stream1,).start() 
    threading.Thread(function=stream2).start() 
    while True: 
     time.sleep(random.randint(0,10)) 
     A = get_main_value1() 
     B = get_main_value2() 
+0

也许这是一个愚蠢的问题:如果我在通过函数设置时需要这个值,该怎么办?会发生什么,或者这是不可能发生的? –

+0

@FroidDymylja我不知道我明白。如果你看我的代码'process2()'返回一个值,然后覆盖'STREAM2_LAST_VALUE'。因此没有中间状态是可能的。 'process2()'也总是看到最后一个值,所以它可以安全地使用它。如果您直接更新到'STREAM2_LAST_VALUE'对象,则可能会出现不一致。 Python中保证了简单读写的一致性。 – freakish

+0

_“在Python中保证简单读写的一致性”_?你能提供一个链接来阅读这个。 – stovfl