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

gh-128679: Fix tracemalloc.stop() race conditions #128893

Merged
merged 1 commit into from
Jan 16, 2025

Conversation

vstinner
Copy link
Member

@vstinner vstinner commented Jan 15, 2025

tracemalloc_alloc(), tracemalloc_realloc(), tracemalloc_free(), _PyTraceMalloc_TraceRef() and _PyTraceMalloc_GetMemory() now check tracemalloc_config.tracing after calling TABLES_LOCK().

_PyTraceMalloc_TraceRef() now always returns 0.

tracemalloc_alloc(), tracemalloc_realloc(), tracemalloc_free(),
_PyTraceMalloc_TraceRef() and _PyTraceMalloc_GetMemory() now check
tracemalloc_config.tracing after calling TABLES_LOCK().

_PyTraceMalloc_TraceRef() now always returns 0.
@vstinner
Copy link
Member Author

@ZeroIntensity: Ok, here is the new fix for #128679 tracemalloc.stop() race condition.

Thanks to #128888 refactoring, the fix is simpler and should be more reliable than my previous attempt. Moreover, this fix is more complete: I fixed more functions.

@vstinner
Copy link
Member Author

For the test, I prefer to use PyThread locks since it's a public API, whereas _Py_LOCK_DONT_DETACH flag of PyMutex is only part of the internal C API.

@ZeroIntensity
Copy link
Member

Ok, that makes sense. We might want to expose that publicly at some point, FWIW.

@ZeroIntensity
Copy link
Member

ZeroIntensity commented Jan 15, 2025

To be perfectly clear--what are the rules for tracemalloc_config.tracing now? Is it now always protected by the tables lock, regardless of the GIL?

@vstinner
Copy link
Member Author

To be perfectly clear--what are the rules for tracemalloc_config.tracing now? Is it now always protected by the tables lock, regardless of the GIL?

It's protected by TABLES_LOCK(). Basically, the whole tracemalloc state is protected by TABLES_LOCK().

The GIL is needed on memory allocations to get the traceback. It's not needed on deallocations.

Copy link
Member

@ZeroIntensity ZeroIntensity left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks!

@vstinner vstinner merged commit 3193cb5 into python:main Jan 16, 2025
43 checks passed
@vstinner vstinner deleted the tracemalloc_stop2 branch January 16, 2025 12:53
@vstinner
Copy link
Member Author

Merged. Thanks for your reviews @ZeroIntensity!

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.

2 participants