Home > Enterprise >  threading.get_ident() returns same ID between different threads when running pytest
threading.get_ident() returns same ID between different threads when running pytest

Time:06-28

I have created a small test case using pytest to demonstrate the issue:

from threading import Thread, get_ident

def test_threading():
    threads = []
    ids = []

    def append_id():
        # time.sleep(1)
        ids.append(get_ident())

    for _ in range(5):
        thread = Thread(target=append_id)
        threads.append(thread)
        thread.start()

    for thread in threads:
        thread.join()

    assert len(set(ids)) == 5

The test is failing because get_ident returns the same ID for different threads. But when I add time.sleep(1) in each thread, the test passes. I'm not sure I understand why.

I'm using Python 3.9.0 and Pytest 7.1.2.

CodePudding user response:

From the documentation of get_ident:

Return the ‘thread identifier’ of the current thread. This is a nonzero integer. Its value has no direct meaning; it is intended as a magic cookie to be used e.g. to index a dictionary of thread-specific data. Thread identifiers may be recycled when a thread exits and another thread is created.

Since your threads are running too quickly (without the time.sleep(1)), the ids are being recycled.

You can provide a name to each thread. This name does not have to be unique, but you can use it in your test (or in your application, if you need something that is unique in a context):

from threading import Thread, get_ident, current_thread

def test_threading():
    threads = []
    names = []
    ids = []

    def append_id():
        # time.sleep(1)
        ids.append(get_ident())
        names.append(current_thread().name)

    for i in range(5):
        thread = Thread(target=append_id, name=f'Thread {i}')
        threads.append(thread)
        thread.start()

    for thread in threads:
        thread.join()

    assert len(set(names)) == 5
    print(f'Names: {names}')
    print(f'Ids: {set(ids)}')
  • Related