Thread secured refcount class.

This commit is contained in:
Jonas 'Sortie' Termansen 2012-08-04 13:50:21 +02:00
parent 61dbb4a2ec
commit 5f93e157d5
2 changed files with 10 additions and 1 deletions

View File

@ -25,6 +25,8 @@
#ifndef SORTIX_REFCOUNT_H
#define SORTIX_REFCOUNT_H
#include <sortix/kernel/kthread.h>
namespace Sortix {
class Refcounted
@ -39,6 +41,7 @@ public:
inline size_t Refcount() const { return refcount; }
private:
kthread_mutex_t reflock;
size_t refcount;
};

View File

@ -23,12 +23,14 @@
*******************************************************************************/
#include <sortix/kernel/platform.h>
#include <sortix/kernel/kthread.h>
#include <sortix/kernel/refcount.h>
namespace Sortix {
Refcounted::Refcounted()
{
reflock = KTHREAD_MUTEX_INITIALIZER;
refcount = 1;
}
@ -41,12 +43,16 @@ Refcounted::~Refcounted()
void Refcounted::Refer()
{
ScopedLock lock(&reflock);
refcount++;
}
void Refcounted::Unref()
{
if ( !--refcount )
kthread_mutex_lock(&reflock);
bool deleteme = !--refcount;
kthread_mutex_unlock(&reflock);
if ( deleteme )
delete this;
}