Files
core_zero/tjp/core/threads/ThreadSafe.hpp
Timothy Prepscius 996151a56a flatten 20260225
2026-02-25 12:43:06 -05:00

66 lines
950 B
C++
Executable File

// License: Modified MIT (NON-AI)
// See the LICENSE file in the root directory for license information.
// Copyright 2025 Timothy Prepscius
#pragma once
#include "Lock.h"
namespace tjp::core {
template<typename T, typename MutexType = Mutex>
struct Accessor;
template<typename T, typename MutexType = Mutex>
struct ThreadSafe
{
using A = Accessor<T, MutexType>;
using A_const = Accessor<const T, MutexType>;
T v;
mutable MutexType mutex;
A access ()
{
return A { &v, &mutex };
}
A_const access () const
{
return A_const { &v, &mutex };
}
template<typename F>
auto with(F &&f)
{
auto lk = lock_of(mutex);
return f(v);
}
} ;
template<typename T, typename MutexType>
struct Accessor
{
using V = ThreadSafe<T, MutexType>;
T *v;
typename MutexType::Lock lock;
Accessor(T *v_, MutexType *m) :
v(v_),
lock(*m)
{
}
T *operator ->()
{
return v;
}
T &operator *()
{
return *v;
}
} ;
} // namespace