task_mutex - Melnytskyi/fast_task GitHub Wiki

Declaration

    class task_mutex {
    public:
        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();
    };

Description

The task_mutex class is a synchronization primitive designed to protect shared data from concurrent access by multiple threads. It is akin to the std::mutex class but tailored for tasks and native threads.

Functions

void lock()

Locks the mutex. If it's already locked by another thread, the current thread will block until the mutex becomes available. Throws std::logic_error if the mutex is already locked by the current task/thread.

bool try_lock()

Tries to lock the mutex. Returns false immediately if another thread has locked the mutex; otherwise, it locks the mutex and returns true. Also returns false in the case of a deadlock.

bool try_lock_for(size_t milliseconds)

Attempts to lock the mutex, waiting for the specified milliseconds if it's already locked. Returns true if the lock is acquired within the timeframe; otherwise, returns false. Also returns false in the case of a deadlock.

void unlock()

Unlocks the mutex. Throws std::logic_error if the mutex is not held by the current task/thread.

bool is_locked()

Attempts to lock and then unlock the mutex. Returns true if the lock is successful, false otherwise.

void lifecycle_lock(const std::shared_ptr<task>& task)

Initiates the task and locks it for its entire lifecycle. The task must not be already started or scheduled.

bool is_own()

Checks if the mutex is locked by the current task/thread, returning true if so, false otherwise.

Example

task_mutex m;
m.lock();
//... critical section
m.unlock();
⚠️ **GitHub.com Fallback** ⚠️