英文:
Python use global variable inside a multiprocessing thread
问题
我试图在两个不同的多进程线程中的两个函数内使用一个变量,但似乎该变量无法共享...
```python
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()
我看到了关于在线程中共享全局变量的不同问题,但它们都没有帮助。
提前感谢
<details>
<summary>英文:</summary>
I'm trying to use a variable inside two functions in two different multiprocessing threads, but it seems that the variable can'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()
I saw different questions about sharing global variables in threads but none of them are helpful.
Thanks in advance
</details>
# 答案1
**得分**: 0
这是我的代码
```python
import threading
threads = []
counter = 0
def my_function():
global counter
while True:
counter += 1
def my_function_two():
global counter
while True:
print(counter)
threads.append(threading.Thread(target=my_function))
threads.append(threading.Thread(target=my_function_two))
for j in threads:
j.start()
for j in threads:
j.join()
英文:
This is my code
import threading
threads = []
counter = 0
def my_function():
global counter
while True:
counter += 1
def my_function_two():
global counter
while True:
print(counter)
threads.append(threading.Thread(target=my_function))
threads.append(threading.Thread(target=my_function_two))
for j in threads:
j.start()
for j in threads:
j.join()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论