Skip to content

test.support.os_helper.EnvironmentVarGuard is not thread safe #132113

@Wulian233

Description

@Wulian233

Bug report

Bug description:

I ran it multiple times with the following code and got different results

Image

import os
import threading
import time
from test.support.os_helper import EnvironmentVarGuard

def worker1(guard):
    for i in range(1000):
        guard['MY_VAR'] = f'value1'
        time.sleep(0.0001)  # Small delay to increase chance of thread switching

def worker2(guard):
    for i in range(1000):
        guard['MY_VAR'] = f'value2'
        time.sleep(0.0001)

guard = EnvironmentVarGuard()
t1 = threading.Thread(target=worker1, args=(guard,))
t2 = threading.Thread(target=worker2, args=(guard,))

t1.start()
t2.start()
t1.join()
t2.join()

final_value = os.getenv('MY_VAR')
print(f"Final value: {final_value}")

This issue I found in #131870, adding a lock to the test_zoneinfo.py, but the original implementation didn't.

BTW, 131870 PR has not been reviewed by anyone yet (more a week)

CPython versions tested on:

3.14, 3.13

Operating systems tested on:

Windows

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibPython modules in the Lib dirtestsTests in the Lib/test dirtype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions