/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
 * The contents of this file are subject to the Netscape Public License
 * Version 1.0 (the "NPL"); you may not use this file except in
 * compliance with the NPL.  You may obtain a copy of the NPL at
 * http://www.mozilla.org/NPL/
 * 
 * Software distributed under the NPL is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
 * for the specific language governing rights and limitations under the
 * NPL.
 * 
 * The Initial Developer of this code under the NPL is Netscape
 * Communications Corporation.  Portions created by Netscape are
 * Copyright (C) 1998 Netscape Communications Corporation.  All Rights
 * Reserved.
 */

/*
**     PR Atomic operations
*/


#include "pratom.h"
#include "primpl.h"

/*
 * The following is a fallback implementation that emulates
 * emulates atomic operations for platforms without atomic
 * operations.  If a platform has atomic operations,
 * it should define the macro _PR_HAVE_ATOMIC_OPS, and
 * the following will not be compiled in.
 */

#ifndef _PR_HAVE_ATOMIC_OPS

/*
 * We use a single lock for all the emulated atomic operations.
 * The lock contention should be acceptable.
 */

static PRLock *monitor = NULL;
void _PR_MD_INIT_ATOMIC()
{
    if (monitor == NULL) {
        monitor = PR_NewLock();
    }
}

PR_IMPLEMENT(PRInt32)
_PR_MD_ATOMIC_INCREMENT(PRInt32 *val)
{
    PRInt32 rv;
    PR_Lock(monitor);
    rv = ++(*val);
    PR_Unlock(monitor);
    return rv;
}

PR_IMPLEMENT(PRInt32)
_PR_MD_ATOMIC_DECREMENT(PRInt32 *val)
{
    PRInt32 rv;
    PR_Lock(monitor);
    rv = --(*val);
    PR_Unlock(monitor);
    return rv;
}

PR_IMPLEMENT(PRInt32)
_PR_MD_ATOMIC_SET(PRInt32 *val, PRInt32 newval)
{
    PRInt32 rv;
    PR_Lock(monitor);
    rv = *val;
    *val = newval;
    PR_Unlock(monitor);
    return rv;
}

#endif  /* !_PR_HAVE_ATOMIC_OPS */

void _PR_InitAtomic(void)
{
    _PR_MD_INIT_ATOMIC();
}

PR_IMPLEMENT(PRInt32)
PR_AtomicIncrement(PRInt32 *val)
{
    return _PR_MD_ATOMIC_INCREMENT(val);
}

PR_IMPLEMENT(PRInt32)
PR_AtomicDecrement(PRInt32 *val)
{
    return _PR_MD_ATOMIC_DECREMENT(val);
}

PR_IMPLEMENT(PRInt32)
PR_AtomicSet(PRInt32 *val, PRInt32 newval)
{
    return _PR_MD_ATOMIC_SET(val, newval);
}

