Skip to content

Commit

Permalink
#1353: make process_iter() thread-safe
Browse files Browse the repository at this point in the history
  • Loading branch information
giampaolo committed Feb 26, 2019
1 parent d912cd5 commit 96091c2
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 5 deletions.
1 change: 1 addition & 0 deletions HISTORY.rst
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ XXXX-XX-XX

**Bug fixes**

- 1353_: process_iter() is now thread safe (it rarely raised TypeError).
- 1394_: [Windows] Process name() and exe() may erronously return "Registry".
QueryFullProcessImageNameW is now used instead of GetProcessImageFileNameW
in order to prevent that.
Expand Down
16 changes: 11 additions & 5 deletions psutil/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1503,6 +1503,7 @@ def pid_exists(pid):


_pmap = {}
_lock = threading.Lock()


def process_iter(attrs=None, ad_value=None):
Expand Down Expand Up @@ -1530,21 +1531,26 @@ def add(pid):
proc = Process(pid)
if attrs is not None:
proc.info = proc.as_dict(attrs=attrs, ad_value=ad_value)
_pmap[proc.pid] = proc
with _lock:
_pmap[proc.pid] = proc
return proc

def remove(pid):
_pmap.pop(pid, None)
with _lock:
_pmap.pop(pid, None)

a = set(pids())
b = set(_pmap.keys())
new_pids = a - b
gone_pids = b - a

for pid in gone_pids:
remove(pid)
for pid, proc in sorted(list(_pmap.items()) +
list(dict.fromkeys(new_pids).items())):

with _lock:
ls = sorted(list(_pmap.items()) +
list(dict.fromkeys(new_pids).items()))

for pid, proc in ls:
try:
if proc is None: # new process
yield add(pid)
Expand Down

0 comments on commit 96091c2

Please sign in to comment.