Skip to content

[libc] implement pthread_mutex_trylock #93359

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

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion libc/src/__support/threads/linux/mutex.h
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,26 @@ struct Mutex {
}
}

MutexError trylock();
MutexError trylock() {
FutexWordType mutex_status = FutexWordType(LockState::Free);
FutexWordType locked_status = FutexWordType(LockState::Locked);
Copy link
Member

Choose a reason for hiding this comment

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

This variable appears unused?


if (futex_word.compare_exchange_strong(mutex_status,
FutexWordType(LockState::Locked))) {
return MutexError::NONE;
}
Comment on lines +123 to +126
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
if (futex_word.compare_exchange_strong(mutex_status,
FutexWordType(LockState::Locked))) {
return MutexError::NONE;
}
if (futex_word.compare_exchange_strong(mutex_status,
FutexWordType(LockState::Locked)))
return MutexError::NONE;

https://llvm.org/docs/CodingStandards.html#don-t-use-braces-on-simple-single-statement-bodies-of-if-else-loop-statements


switch (LockState(mutex_status)) {
case LockState::Locked:
if (recursive && this == owner) {
lock_count++;
}
Comment on lines +130 to +132
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
if (recursive && this == owner) {
lock_count++;
}
if (recursive && this == owner)
lock_count++;

Though I think we don't care what the resulting mutex_status value is if it's NOT Lock state::Locked, we should simply return MutexError::BUSY;.

return MutexError::NONE;
case LockState::Free:
// If it was LockState::Free, we shouldn't be here at all.
return MutexError::BAD_LOCK_STATE;
}
}
};

} // namespace LIBC_NAMESPACE
Expand Down
Loading