X Tutup
The Wayback Machine - https://web.archive.org/web/20250811150037/https://github.com/python/cpython/issues/121512
Skip to content

os.sched_yield() + range() unexpected influence #121512

@socketpair

Description

@socketpair

Bug report

Bug description:

The counters printed are expected to be almost the same. They are. But some arguments for range(), sched_yield() significantly change the picture. Note, sched_yield() slows down ANOTHER thread, and unexpectedly speeds up the current one.

python3 --version
Python 3.12.3
Linux Fedora 39, kernel 6.9.4-100.fc39.x86_64
from os import sched_yield
from queue import SimpleQueue
from threading import Thread
from time import monotonic

period = 2


def _thread(queue1: SimpleQueue) -> None:
    consumed = 0
    start = monotonic()
    while queue1.get():
        consumed += 1
    end = monotonic()
    print(f'Consumed: {consumed / 1000 / (end - start):12.2f} Kitems/sec.')


def main():
    for arg in (1, 10, 100, 1000, 10_000, 100_000, 1000_000, 10_000_000):
        print(f'Testing for {arg=}')
        queue: SimpleQueue[bool] = SimpleQueue()
        thread = Thread(target=_thread, args=(queue,), daemon=True)
        thread.start()
        cnt = 0
        deadline = monotonic() + period
        while monotonic() < deadline:
            for i in range(arg):
                cnt += 1
                if queue.qsize() <= 1048576:
                    queue.put(True)
            sched_yield()  # with commented out - no bugs for any `range()`
            # time.sleep(0) # no bugs for any `range()`
        stop = monotonic()
        queue.put(False)
        thread.join()
        print(f'Produced: {cnt / 1000 / (stop - (deadline - period)):12.2f} Kitems/sec.')


main()
Testing for arg=1
Consumed:       644.82 Kitems/sec.
Produced:       644.83 Kitems/sec.
Testing for arg=10
Consumed:      3981.64 Kitems/sec.
Produced:      3981.68 Kitems/sec.
Testing for arg=100
Consumed:      3809.66 Kitems/sec.  <----- BUG
Produced:     15519.08 Kitems/sec.
Testing for arg=1000
Consumed:      1192.78 Kitems/sec.  <----- BUG
Produced:     19605.59 Kitems/sec.
Testing for arg=10000
Consumed:       585.87 Kitems/sec.  <----- BUG
Produced:     19829.86 Kitems/sec.
Testing for arg=100000
Consumed:     10839.18 Kitems/sec.
Produced:     10883.60 Kitems/sec.
Testing for arg=1000000
Consumed:     11005.64 Kitems/sec.
Produced:     11011.80 Kitems/sec.
Testing for arg=10000000
Consumed:     10800.30 Kitems/sec.
Produced:     10805.39 Kitems/sec.

CPython versions tested on:

3.12

Operating systems tested on:

Linux

Metadata

Metadata

Assignees

Labels

type-bugAn unexpected behavior, bug, or error

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions

    X Tutup