Python在多进程线程中使用全局变量

huangapple go评论129阅读模式
英文:

Python use global variable inside a multiprocessing thread

问题

  1. 我试图在两个不同的多进程线程中的两个函数内使用一个变量,但似乎该变量无法共享...
  2. ```python
  3. import multiprocessing
  4. threads = []
  5. counter = 0
  6. def my_function():
  7. global counter
  8. while True:
  9. counter += 1
  10. def my_function_two():
  11. global counter
  12. while True:
  13. print(counter)
  14. threads.append(multiprocessing.Process(target=my_function))
  15. threads.append(multiprocessing.Process(target=my_function_two))
  16. for j in threads:
  17. j.start()
  18. for j in threads:
  19. j.join()

我看到了关于在线程中共享全局变量的不同问题,但它们都没有帮助。

提前感谢

  1. <details>
  2. <summary>英文:</summary>
  3. I&#39;m trying to use a variable inside two functions in two different multiprocessing threads, but it seems that the variable can&#39;t be shared...

import multiprocessing

threads = []
counter = 0

def my_function():
global counter
while True:
counter += 1

def my_function_two():
global counter
while True:
print(counter)

threads.append(multiprocessing.Process(target=my_function))
threads.append(multiprocessing.Process(target=my_function_two))

for j in threads:
j.start()

for j in threads:
j.join()

  1. I saw different questions about sharing global variables in threads but none of them are helpful.
  2. Thanks in advance
  3. </details>
  4. # 答案1
  5. **得分**: 0
  6. 这是我的代码
  7. ```python
  8. import threading
  9. threads = []
  10. counter = 0
  11. def my_function():
  12. global counter
  13. while True:
  14. counter += 1
  15. def my_function_two():
  16. global counter
  17. while True:
  18. print(counter)
  19. threads.append(threading.Thread(target=my_function))
  20. threads.append(threading.Thread(target=my_function_two))
  21. for j in threads:
  22. j.start()
  23. for j in threads:
  24. j.join()
英文:

This is my code

  1. import threading
  2. threads = []
  3. counter = 0
  4. def my_function():
  5. global counter
  6. while True:
  7. counter += 1
  8. def my_function_two():
  9. global counter
  10. while True:
  11. print(counter)
  12. threads.append(threading.Thread(target=my_function))
  13. threads.append(threading.Thread(target=my_function_two))
  14. for j in threads:
  15. j.start()
  16. for j in threads:
  17. j.join()

huangapple
  • 本文由 发表于 2023年7月20日 15:51:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76727737.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定