shared_map.hh 2.31 KB
Newer Older
1
2
// graph-tool -- a general graph modification and manipulation thingy
//
Tiago Peixoto's avatar
Tiago Peixoto committed
3
// Copyright (C) 2006-2017 Tiago de Paula Peixoto <tiago@skewed.de>
4
5
6
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
Tiago Peixoto's avatar
Tiago Peixoto committed
7
// as published by the Free Software Foundation; either version 3
8
9
10
11
12
13
14
15
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
16
// along with this program. If not, see <http://www.gnu.org/licenses/>.
17
18
19
20

#ifndef SHARED_MAP_HH
#define SHARED_MAP_HH

21
22
// This class will encapsulate a map, and atomically sum it to a given resulting
// map (which is shared among all copies) after it is destructed, or when the
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// Gather() member function is called. This enables, for instance, a histogram
// to built in parallel.

template <class Map>
class SharedMap: public Map
{
public:
    SharedMap(Map &map):_sum(&map) {}
    ~SharedMap()
    {
        Gather();
    }

    void Gather()
    {
        if (_sum != 0)
        {
40
            for (decltype(this->begin()) iter = this->begin();
41
                 iter != this->end(); ++iter)
42
43
44
45
46
47
48
49
50
51
52
53
54
            {
                #pragma omp critical
                {
                    (*_sum)[iter->first] += iter->second;
                }
            }
            _sum = 0;
        }
    }
private:
    Map* _sum;
};

55
56
57
58
// This class will encapsulate a generic container, such as a vector or list,
// and atomically concatenate it to a given resulting container (which is shared
// among all copies) after it is destructed, or when the Gather() member
// function is called.
Tiago Peixoto's avatar
   
Tiago Peixoto committed
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73

template <class Container>
class SharedContainer: public Container
{
public:
    SharedContainer(Container &cont): _sum(&cont) {}
    ~SharedContainer()
    {
        Gather();
    }

    void Gather()
    {
        if (_sum != 0)
        {
74
            #pragma omp critical
Tiago Peixoto's avatar
   
Tiago Peixoto committed
75
            {
76
77
                for (auto& x : *this)
                    _sum->push_back(x);
Tiago Peixoto's avatar
   
Tiago Peixoto committed
78
79
80
81
82
83
84
85
86
            }
            _sum = 0;
        }
    }
private:
    Container* _sum;
};


87
#endif //SHARED_MAP_HH