summaryrefslogtreecommitdiff
path: root/src/stable/synchrocounter.h
blob: 17de89045056b4a2888fc6b0648d7a23bd9f5b26 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/*
 * Copyright (C) 2007-2012 Xagasoft, All rights reserved.
 *
 * This file is part of the libbu++ library and is released under the
 * terms of the license contained in the file LICENSE.
 */

#ifndef BU_SYNCHRO_COUNTER_H
#define BU_SYNCHRO_COUNTER_H

#include "bu/mutex.h"

namespace Bu
{
    /**
     * A simple thread-safe counter class.  This is handy for assigning unique
     * IDs to objects that are being created in different threads.
     *@ingroup Threading Containers
     */
    template <class T>
    class SynchroCounter
    {
    public:
        SynchroCounter() :
            tCounter( 0 )
        {
        }
        
        virtual ~SynchroCounter()
        {
        }

        T next()
        {
            mOperate.lock();
            T tRet = tCounter;
            tCounter++;
            mOperate.unlock();

            return tRet;
        }

    private:
        T tCounter;             /**< The counter itself. */
        Mutex mOperate; /**< The master mutex, used on all operations. */
    };
}

#endif