task_recursive_mutex - Melnytskyi/fast_task GitHub Wiki
class task_recursive_mutex {
public:
task_recursive_mutex() = default;
~task_recursive_mutex();
void lock();
bool try_lock();
bool try_lock_for(size_t milliseconds);
bool try_lock_until(std::chrono::high_resolution_clock::time_point time_point);
void unlock();
bool is_locked();
void lifecycle_lock(const std::shared_ptr<task>& task);
bool is_own();
};
The task_recursive_mutex class is a synchronization primitive that can be locked multiple times by the same task or thread without causing a deadlock. If a task or thread locks the mutex and then attempts to lock it again, the operation will succeed, and the recursive_count will be incremented. The mutex is only actually released when unlock is called as many times as lock was called.
task_recursive_mutex()
Default constructor initializes the mutex without locking it.
void lock()
Locks the mutex. If the mutex is already locked by the current task or thread, increments recursive_count.
bool try_lock()
Tries to lock the mutex without blocking. Returns true if the lock was successful.
bool try_lock_for(size_t milliseconds)
Attempts to lock the mutex, blocking for a specified duration if it is already locked. Returns true if the lock was acquired.
bool try_lock_until(std::chrono::high_resolution_clock::time_point time_point)
Attempts to lock the mutex, blocking until a specified time point if it is already locked. Returns true if the lock was acquired.
void unlock()
Unlocks the mutex. If recursive_count is greater than one, it decrements it instead of unlocking the mutex.
bool is_locked()
Returns true if the mutex is currently locked.
void lifecycle_lock(const std::shared_ptr<task>& task)
Locks the mutex and associates it with the lifecycle of the given task. The mutex will be unlocked when the task is finished.
bool is_own()
Checks if the current task or thread is the owner of the mutex. Returns true if it is.
void task_function(std::shared_ptr<task_recursive_mutex> mutex) {
if(mutex->is_own()) {
std::cout << "Task is already executing with mutex locked." << std::endl;
}
mutex->lock();
std::cout << "Task is executing with mutex locked." << std::endl;
mutex->unlock();
}
int main() {
auto mutex = std::make_shared<task_recursive_mutex>();
auto my_task = std::make_shared<task>([&]() { task_function(mutex); });
mutex->lifecycle_lock(my_task);
task::await_task(my_task);
if (!mutex->is_locked()) {
std::cout << "Mutex is unlocked after task completion." << std::endl;
}
return 0;
}