Python线程:线程运行两次?

2024-04-24 23:37:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我对python完全陌生,当我遇到这个问题时,我正在尝试线程模块: -由于某种原因,线程运行两次,我不知道为什么。我到处找,但没找到答案。 希望我能在这里得到一些帮助

import time
from threading import Thread
import requests as requests
import threading as threading 


threads = []
i = 0
time.sleep(0.5)
def whatever():
    global i
    while i < 10:
        get = requests.get("http://www.exemple.com")
        print(i)
        i += 1

for t in range(5):
    t = threading.Thread(target=whatever)
    threads.append(t)
    t.start()

我想要的:

^{pr2}$

输出:

0
1
1
3
4
5
6
7
7
9
10
11
12
13

Tags: 模块答案fromimportgettimeassleep
1条回答
网友
1楼 · 发布于 2024-04-24 23:37:18

从多个线程修改全局变量本质上是不安全的。您需要锁定访问以防止争用情况,例如线程a读取i,然后线程B运行并递增i并将其存储回,然后线程a返回并存储其递增的i副本,因此它不是递增两次,而是递增一次。在

解决方法是要么锁定访问,要么想出一种天生的线程安全的方法来做你想做的事情。在CPython引用解释器中,可以保证字节码之间没有GIL版本,因此有一些技巧可以在不使用锁的情况下完成此操作:

import time
from threading import Thread

threads = []
igen = iter(range(10))
time.sleep(0.5)
def whatever():
    for i in igen:
        get = requests.get("http://www.exemple.com")
        print(i)

for t in range(5):
    t = threading.Thread(target=whatever)
    threads.append(t)
    t.start()

使用锁更为复杂,但对于任何具有可预测(ish,毕竟还是线程)行为的Python解释器来说,应该是可移植的:

^{pr2}$

这不会以数字顺序打印出来,但它将并行运行请求,并且只会为i打印一次给定的值。在

相关问题 更多 >