File: lazy_emplace_l.cc

package info (click to toggle)
parallel-hashmap 1.4.1%2Bds-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,872 kB
  • sloc: cpp: 20,492; ansic: 1,114; python: 492; makefile: 85; haskell: 56; perl: 43; sh: 23
file content (45 lines) | stat: -rw-r--r-- 1,504 bytes parent folder | download
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
// ------------------------
// Windows specific example 
// curtesy of @kanonka
// ------------------------
#include <windows.h>
#include "parallel_hashmap/phmap.h"
#include <cstring>
#include <vector>
#include <ppl.h>

using Map =  phmap::parallel_flat_hash_map<std::string, int, phmap::priv::hash_default_hash<std::string>,
                                           phmap::priv::hash_default_eq<std::string>,
                                           std::allocator<std::pair<const std::string, int>>, 8, phmap::srwlock>;

class Dict
{
    Map m_stringsMap;

public:
    int addParallel(std::string&& str, volatile long* curIdx)
    {
        int newIndex = -1;
        m_stringsMap.lazy_emplace_l(std::move(str),
                                    [&](Map::value_type& p) { newIndex = p.second; },  // called only when key was already present
                                    [&](const Map::constructor& ctor) // construct value_type in place when key not present
                                        { newIndex = InterlockedIncrement(curIdx); ctor(std::move(str), newIndex); }); 

        return newIndex;
    }
};

int main()
{
    size_t totalSize = 6000000;
    std::vector<int> values(totalSize);
    Dict dict;
    volatile long index = 0;
    concurrency::parallel_for(size_t(0), size_t(totalSize), 
        [&](size_t i) {
            std::string s = "ab_uu_" + std::to_string(i % 1000000);
            values[i] = dict.addParallel(std::move(s), &index);
        });

    return 0;
}