/*========================== begin_copyright_notice ============================
Copyright (C) 2021 Intel Corporation

SPDX-License-Identifier: MIT
============================= end_copyright_notice ===========================*/

#pragma once

#ifndef PIN_CRT
# include <mutex>
using std::mutex;
using std::lock_guard;
#else
# include <os-apis/mutex.h>

class mutex
{
public:
    mutex()
    {
        OS_MutexInit(&m_lock);
    }

    ~mutex()
    {
        OS_MutexDestroy(&m_lock);
    }
    mutex(const mutex&) = delete;
    mutex& operator=(const mutex&) = delete;

    void lock()
    {
        OS_MutexLock(&m_lock);
    }

    void unlock()
    {
        OS_MutexUnlock(&m_lock);
    }
private:
    OS_MUTEX_TYPE m_lock;
};

template <class _Mutex>
class lock_guard { // class with destructor that unlocks a mutex
public:
    using mutex_type = _Mutex;

    explicit lock_guard(_Mutex& _Mtx) : _MyMutex(_Mtx) { // construct and lock
        _MyMutex.lock();
    }

    ~lock_guard() { // unlock
        _MyMutex.unlock();
    }

    lock_guard(const lock_guard&) = delete;
    lock_guard& operator=(const lock_guard&) = delete;

private:
    _Mutex& _MyMutex;
};
#endif