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

Add *new_only* parameter for process_iter() #1667

Merged
merged 3 commits into from Jan 18, 2020
Merged

Conversation

giampaolo
Copy link
Owner

When true, process_iter() will yield new process only (meaning new PIDs appeared since last call):

>>> import psutil
>>> for proc in psutil.process_iter(attrs=['pid', 'name'], new_only=True):
...     print(proc.info)
...

This comes from a real-world use case I bumped into: I spawn a subprocess but don't know its PID, so I look for it by checking the command line of all processes. Instead of iterating over all processes, I want to iterate over new PIDs only (faster).

@giampaolo giampaolo merged commit ef28cae into master Jan 18, 2020
@giampaolo giampaolo deleted the process-iter-new-only branch January 18, 2020 12:04
giampaolo added a commit that referenced this pull request Feb 18, 2020
On a second thought I realized that process_iter() uses a global
variable, so it's not thread safe.
That means that if the are 2 threads using it, the first thread one calling the function (+ consume the iterator), will "steal" the processes of the second thread.

psutil.cpu_percent() has the same problem. That means we have a problem
can't solve with the current API and requires a lot of thinking on how
to solve it as it's not obvious.
@giampaolo
Copy link
Owner Author

On a second thought, I realized that process_iter() uses a global variable, so it's not thread safe.
Despite this is acceptable when using it in the standard way, this case is different: if the are 2 threads using process_iter(), the first one calling it (+ consuming the iterator) will "steal" the processes of the second thread. That aside, it's unclear how to solve this problem in terms of API, so I reverted this PR in c9fc4fd. Problem solved.

We have another one though: psutil.cpu_percent(). Since it also uses a global var, multiple threads will "reset" the internal timings of each other and invalidate result. Not sure why I realized this only now but the doc should be more clear about this.

Anyway, I'll discuss this in another ticket.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant