File: spinlock.cpp

package info (click to toggle)
yrmcds 1.0.4-6
  • links: PTS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 924 kB
  • ctags: 1,346
  • sloc: cpp: 9,634; sh: 133; makefile: 97
file content (29 lines) | stat: -rw-r--r-- 577 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
#include <cybozu/spinlock.hpp>

#include <mutex>
#include <thread>
#include <iostream>

alignas(CACHELINE_SIZE)
cybozu::spinlock g_lock;

alignas(CACHELINE_SIZE)
unsigned int g_counter = 0;

void accum(int n) {
    for(int i = 0; i < n; ++i) {
        std::lock_guard<cybozu::spinlock> guard(g_lock);
        ++g_counter;
    }
}

int main() {
    std::thread t1(accum, 100000);
    std::thread t2(accum, 100000);
    std::thread t3(accum, 100000);
    t1.join();
    t2.join();
    t3.join();
    std::cout << "accumulated value = " << g_counter << std::endl;
    return 0;
}