如何使用从线程1到线程2的变量

问题描述 投票:0回答:1

我需要使用python将变量从线程1传递给线程2。我该怎么做?让我通过一个小代码来证明这个问题。

import time
import threading
print_lock = threading.Lock()
def hi(a,b):
   c = a + b
   with print_lock:
      print(c)
   time.sleep(1)
def hello(e,f):
   ans = e + f
   with print_lock:
      print(ans)
      #suppose if I had to print variable 'a' from hi function over here.
   time.sleep(1)
t1 = threading.Thread(target=hi, args=(2,3))
t2 = threading.Thread(target=hello, args=(6,7))
t1.start()
t2.start()
t1.join()
t2.join()

以上程序非常简单。 def hi()是一个主题。 def hello()是另一个主题。如果我必须从a函数中的hi函数访问变量hello。我该怎么做?

python python-3.x multithreading python-multithreading
1个回答
0
投票

您应该将变量定义为global。但是你应该记住,共享变量不是线程安全的。因此,在对变量执行任何操作之前,应始终锁定。否则你的程序会表现出不同的一切。

假设您正在对变量a进行一些操作,该变量在不同的线程中更新,那么在对变量进行更新之前需要对变量进行锁定

a = 1
lock = threading.Lock()
def foo():
    global a
    for i in range(1000000):
        with lock:
            a*=2
© www.soinside.com 2019 - 2024. All rights reserved.