Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Linux] Race condition in Process.threads() #2150

Closed
li-dan opened this issue Sep 29, 2022 · 0 comments · Fixed by #2151
Closed

[Linux] Race condition in Process.threads() #2150

li-dan opened this issue Sep 29, 2022 · 0 comments · Fixed by #2151

Comments

@li-dan
Copy link
Contributor

li-dan commented Sep 29, 2022

Summary

  • OS: Linux
  • Architecture: 64bit
  • Psutil version: 5.9.3
  • Python version: 3.10.4
  • Type: core

Description

Process.threads() has a race condition in this code:

psutil/psutil/_pslinux.py

Lines 2061 to 2068 in 69b572e

try:
with open_binary(fname) as f:
st = f.read().strip()
except FileNotFoundError:
# no such file or directory; it means thread
# disappeared on us
hit_enoent = True
continue

A thread may exit after the open_binary() call and before the read() call. In this case open_binary() will succeed but read() will raise ProcessLookupError.

I think this should be treated the same as FileNotFoundError from open_binary(), since in both cases it means the thread disappeared on us.

Here's some code I used to trigger the race condition:

import psutil
import random
import threading
import time

def noop():
    time.sleep(random.random() * 10)

def generate_threads():
    for _ in range(10):
        threads = []
        for _ in range(100):
            thread = threading.Thread(target=noop)
            thread.start()
            threads.append(thread)
        for thread in threads:
            thread.join()

t = threading.Thread(target=generate_threads)
t.start()

while t.is_alive():
    psutil.Process().threads()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant