Skip to content

gh-135239: smarter use of mutex in _md5 #135267

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

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from

Conversation

picnixz
Copy link
Member

@picnixz picnixz commented Jun 8, 2025

I've taken the liberty of normalizing code style. I'll do the same in other modules, (SHA and BLAKE2). That way, I'll never need to touch cosmetics again in crypto-modules. Well, if it's too much I can drop the last commit.

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.

Note that PyMutex_Lock will release the GIL/detach the thread state anyway. You want _PyMutex_LockFlags(m, _Py_LOCK_DONT_DETACH) if you're worried about GIL overhead.

static void
md5_update_state_cond_lock(MD5object *self, uint8_t *buf, Py_ssize_t len)
{
ENTER_HASHLIB(self); // conditionally acquire a lock
Copy link
Member

Choose a reason for hiding this comment

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

I might be misunderstanding this, but this will never lock on the GIL-ful build, and always lock on free-threading? If that's the case, why not just wrap the lock with a Py_GIL_DISABLED instead of a use_mutex field?

If it's not like that, and you can indeed arbitarily modify use_mutex at runtime, then this isn't thread-safe: use_mutex might get concurrently reassigned, which will lead to deadlocks and worse.

Copy link
Member Author

@picnixz picnixz Jun 8, 2025

Choose a reason for hiding this comment

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

If it's not like that, and you can indeed arbitarily modify use_mutex at runtime,

Not arbitrarily but it's possible to set use_mutex to true if we give a large data to hash.

Copy link
Member Author

Choose a reason for hiding this comment

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

But let me actually think about it tomorrow. I feel that I actually messed up my conditions somewhere.

Copy link
Member

Choose a reason for hiding this comment

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

I think a general good rule of thumb is that conditional locking is evil.

@picnixz picnixz marked this pull request as draft June 8, 2025 19:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
skip news type-refactor Code refactoring (with no changes in behavior)
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants