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

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

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&#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()

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()

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:

确定