├── LICENSE
├── Makefile
├── README.md
└── src
├── main.cpp
└── shared_mutex.h
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU LESSER GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 |
9 | This version of the GNU Lesser General Public License incorporates
10 | the terms and conditions of version 3 of the GNU General Public
11 | License, supplemented by the additional permissions listed below.
12 |
13 | 0. Additional Definitions.
14 |
15 | As used herein, "this License" refers to version 3 of the GNU Lesser
16 | General Public License, and the "GNU GPL" refers to version 3 of the GNU
17 | General Public License.
18 |
19 | "The Library" refers to a covered work governed by this License,
20 | other than an Application or a Combined Work as defined below.
21 |
22 | An "Application" is any work that makes use of an interface provided
23 | by the Library, but which is not otherwise based on the Library.
24 | Defining a subclass of a class defined by the Library is deemed a mode
25 | of using an interface provided by the Library.
26 |
27 | A "Combined Work" is a work produced by combining or linking an
28 | Application with the Library. The particular version of the Library
29 | with which the Combined Work was made is also called the "Linked
30 | Version".
31 |
32 | The "Minimal Corresponding Source" for a Combined Work means the
33 | Corresponding Source for the Combined Work, excluding any source code
34 | for portions of the Combined Work that, considered in isolation, are
35 | based on the Application, and not on the Linked Version.
36 |
37 | The "Corresponding Application Code" for a Combined Work means the
38 | object code and/or source code for the Application, including any data
39 | and utility programs needed for reproducing the Combined Work from the
40 | Application, but excluding the System Libraries of the Combined Work.
41 |
42 | 1. Exception to Section 3 of the GNU GPL.
43 |
44 | You may convey a covered work under sections 3 and 4 of this License
45 | without being bound by section 3 of the GNU GPL.
46 |
47 | 2. Conveying Modified Versions.
48 |
49 | If you modify a copy of the Library, and, in your modifications, a
50 | facility refers to a function or data to be supplied by an Application
51 | that uses the facility (other than as an argument passed when the
52 | facility is invoked), then you may convey a copy of the modified
53 | version:
54 |
55 | a) under this License, provided that you make a good faith effort to
56 | ensure that, in the event an Application does not supply the
57 | function or data, the facility still operates, and performs
58 | whatever part of its purpose remains meaningful, or
59 |
60 | b) under the GNU GPL, with none of the additional permissions of
61 | this License applicable to that copy.
62 |
63 | 3. Object Code Incorporating Material from Library Header Files.
64 |
65 | The object code form of an Application may incorporate material from
66 | a header file that is part of the Library. You may convey such object
67 | code under terms of your choice, provided that, if the incorporated
68 | material is not limited to numerical parameters, data structure
69 | layouts and accessors, or small macros, inline functions and templates
70 | (ten or fewer lines in length), you do both of the following:
71 |
72 | a) Give prominent notice with each copy of the object code that the
73 | Library is used in it and that the Library and its use are
74 | covered by this License.
75 |
76 | b) Accompany the object code with a copy of the GNU GPL and this license
77 | document.
78 |
79 | 4. Combined Works.
80 |
81 | You may convey a Combined Work under terms of your choice that,
82 | taken together, effectively do not restrict modification of the
83 | portions of the Library contained in the Combined Work and reverse
84 | engineering for debugging such modifications, if you also do each of
85 | the following:
86 |
87 | a) Give prominent notice with each copy of the Combined Work that
88 | the Library is used in it and that the Library and its use are
89 | covered by this License.
90 |
91 | b) Accompany the Combined Work with a copy of the GNU GPL and this license
92 | document.
93 |
94 | c) For a Combined Work that displays copyright notices during
95 | execution, include the copyright notice for the Library among
96 | these notices, as well as a reference directing the user to the
97 | copies of the GNU GPL and this license document.
98 |
99 | d) Do one of the following:
100 |
101 | 0) Convey the Minimal Corresponding Source under the terms of this
102 | License, and the Corresponding Application Code in a form
103 | suitable for, and under terms that permit, the user to
104 | recombine or relink the Application with a modified version of
105 | the Linked Version to produce a modified Combined Work, in the
106 | manner specified by section 6 of the GNU GPL for conveying
107 | Corresponding Source.
108 |
109 | 1) Use a suitable shared library mechanism for linking with the
110 | Library. A suitable mechanism is one that (a) uses at run time
111 | a copy of the Library already present on the user's computer
112 | system, and (b) will operate properly with a modified version
113 | of the Library that is interface-compatible with the Linked
114 | Version.
115 |
116 | e) Provide Installation Information, but only if you would otherwise
117 | be required to provide such information under section 6 of the
118 | GNU GPL, and only to the extent that such information is
119 | necessary to install and execute a modified version of the
120 | Combined Work produced by recombining or relinking the
121 | Application with a modified version of the Linked Version. (If
122 | you use option 4d0, the Installation Information must accompany
123 | the Minimal Corresponding Source and Corresponding Application
124 | Code. If you use option 4d1, you must provide the Installation
125 | Information in the manner specified by section 6 of the GNU GPL
126 | for conveying Corresponding Source.)
127 |
128 | 5. Combined Libraries.
129 |
130 | You may place library facilities that are a work based on the
131 | Library side by side in a single library together with other library
132 | facilities that are not Applications and are not covered by this
133 | License, and convey such a combined library under terms of your
134 | choice, if you do both of the following:
135 |
136 | a) Accompany the combined library with a copy of the same work based
137 | on the Library, uncombined with any other library facilities,
138 | conveyed under the terms of this License.
139 |
140 | b) Give prominent notice with the combined library that part of it
141 | is a work based on the Library, and explaining where to find the
142 | accompanying uncombined form of the same work.
143 |
144 | 6. Revised Versions of the GNU Lesser General Public License.
145 |
146 | The Free Software Foundation may publish revised and/or new versions
147 | of the GNU Lesser General Public License from time to time. Such new
148 | versions will be similar in spirit to the present version, but may
149 | differ in detail to address new problems or concerns.
150 |
151 | Each version is given a distinguishing version number. If the
152 | Library as you received it specifies that a certain numbered version
153 | of the GNU Lesser General Public License "or any later version"
154 | applies to it, you have the option of following the terms and
155 | conditions either of that published version or of any later version
156 | published by the Free Software Foundation. If the Library as you
157 | received it does not specify a version number of the GNU Lesser
158 | General Public License, you may choose any version of the GNU Lesser
159 | General Public License ever published by the Free Software Foundation.
160 |
161 | If the Library as you received it specifies that a proxy can decide
162 | whether future versions of the GNU Lesser General Public License shall
163 | apply, that proxy's public statement of acceptance of any version is
164 | permanent authorization for you to choose that version for the
165 | Library.
166 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | #Makefile generated by amake
2 | #On Thu Aug 31 18:05:46 2017
3 | #To print amake help use 'amake --help'.
4 | CC=gcc
5 | CPPC=g++
6 | LINK=g++
7 | SRCDIR=src
8 | OBJDIR=obj
9 | LEVEL1_DCACHE_LINESIZE=$(shell getconf LEVEL1_DCACHE_LINESIZE)
10 | FLAGS=-g -Wall -std=c++11 -pthread -DLEVEL1_DCACHE_LINESIZE=$(LEVEL1_DCACHE_LINESIZE)
11 | LIBS=
12 | OBJS=$(OBJDIR)/main.o
13 | EXEC=shared_mutex
14 | DATE=$(shell date +"%Y-%m-%d")
15 |
16 | $(EXEC) : $(OBJS)
17 | $(LINK) $(OBJS) -o $(EXEC) $(FLAGS) $(LIBS)
18 |
19 | $(OBJDIR)/main.o: src/main.cpp src/shared_mutex.h $(OBJDIR)/__setup_obj_dir
20 | $(CPPC) $(FLAGS) src/main.cpp -c -o $@
21 |
22 | $(OBJDIR)/__setup_obj_dir :
23 | mkdir -p $(OBJDIR)
24 | touch $(OBJDIR)/__setup_obj_dir
25 |
26 | .PHONY: clean bzip release
27 |
28 | clean :
29 | rm -rf $(OBJDIR)/*.o
30 | rm -rf $(EXEC)
31 |
32 | bzip :
33 | tar -cvf "$(DATE).$(EXEC).tar" $(SRCDIR)/* Makefile
34 | bzip2 "$(DATE).$(EXEC).tar"
35 |
36 | release : FLAGS +=-O3 -D_RELEASE
37 | release : $(EXEC)
38 |
39 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # shared_mutex
2 | A C++11 shared mutex with high emphasis on performance.
3 |
4 | Please note this is a template library (released under LGPLv3) hence the main itself is simply a test to show the performance against a `std::mutex`; the current version compiles on Linux, still it should be easy to adapt to Windows or other architectures.
5 |
6 | ## Building
7 | Simply invoke `make` (`make release` for optimized build) and the main should compile.
8 |
9 | ## Running
10 | The main is a simple test for performance. What is does is sharing two `size_t` variables and then increment them from one thread evey *w_freq* loops and just reading both of them from other threads.
11 | This is to reproduce the test case of *many R/O - less R/W*, where this kind of `ema::shared_mutex` excels.
12 |
13 | Output is going to be a sort-of-table showing the performance of the benchmark. As example
14 | ```
15 | real, user, sys, mutex_type
16 | 2.48, 5.10, 3.52, ema::shared_mutex (4,33554432,1024,4)
17 | 12.18, 18.05, 27.29, std::mutex (4,33554432,1024,4)
18 | 2.38, 5.16, 3.29, ema::shared_mutex (4,33554432,512,4)
19 | 11.89, 17.33, 26.68, std::mutex (4,33554432,512,4)
20 | 2.96, 5.87, 4.50, ema::shared_mutex (4,33554432,256,4)
21 | 11.87, 17.54, 26.44, std::mutex (4,33554432,256,4)
22 | 3.03, 6.31, 4.76, ema::shared_mutex (4,33554432,128,4)
23 | 12.08, 17.77, 27.19, std::mutex (4,33554432,128,4)
24 | 5.02, 10.69, 8.58, ema::shared_mutex (4,33554432,16,4)
25 | 12.51, 18.30, 28.25, std::mutex (4,33554432,16,4)
26 | 8.59, 18.08, 13.08, ema::shared_mutex (4,33554432,4,4)
27 | 12.71, 18.98, 28.04, std::mutex (4,33554432,4,4)
28 | ```
29 | Where for every row, you have total *real*, *user* and *system* time (in seconds), the type of mutex and then between brackets how many threads, how many iterations, frequency of writing (i.e. every *x* iterations) and how many threads are allowed to write.
30 |
31 | As example, on my [i7-3770k](http://ark.intel.com/products/65523/Intel-Core-i7-3770K-Processor-8M-Cache-up-to-3_90-GHz) (not overclocked) in order for 4 threads to run, execute 32M loops, each thread modify the variables every 1024 iterations, took:
32 | - 2.48 s *real* (a.k.a. wall) time
33 | - 5.1 s *user* time
34 | - 3.52 s *system* time
35 |
36 | The same when using a `std::mutex` has been:
37 | - 12.18 s *real* (a.k.a. wall) time
38 | - 18.05 s *user* time
39 | - 27.29 s *system* time
40 |
41 | Quite the **difference**, isn't it? :-)
42 |
43 | *Updates*
44 |
45 | Moved my rig to a [5950x](https://www.amd.com/en/products/cpu/amd-ryzen-9-5950x) and run the same test (4 threads):
46 | ```
47 | real, user, sys, mutex_type
48 | 0.29, 0.93, 0.16, ema::shared_mutex (4,33554432,1024,4)
49 | 4.06, 5.51, 9.51, std::mutex (4,33554432,1024,4)
50 | 0.38, 1.12, 0.30, ema::shared_mutex (4,33554432,512,4)
51 | 4.23, 5.66, 10.02, std::mutex (4,33554432,512,4)
52 | 0.51, 1.45, 0.49, ema::shared_mutex (4,33554432,256,4)
53 | 4.28, 5.57, 10.28, std::mutex (4,33554432,256,4)
54 | 0.84, 2.25, 0.80, ema::shared_mutex (4,33554432,128,4)
55 | 4.60, 5.81, 11.11, std::mutex (4,33554432,128,4)
56 | 3.03, 7.62, 3.52, ema::shared_mutex (4,33554432,16,4)
57 | 6.95, 7.93, 17.04, std::mutex (4,33554432,16,4)
58 | 10.75, 27.50, 13.37, ema::shared_mutex (4,33554432,4,4)
59 | 7.32, 8.24, 17.58, std::mutex (4,33554432,4,4)
60 | ```
61 | And then with 16 threads (number of physical cores on this CPU):
62 | ```
63 | real, user, sys, mutex_type
64 | 1.29, 8.23, 8.01, ema::shared_mutex (16,33554432,1024,16)
65 | 15.72, 22.81,215.80, std::mutex (16,33554432,1024,16)
66 | 1.97, 12.93, 12.56, ema::shared_mutex (16,33554432,512,16)
67 | 16.38, 23.04,228.58, std::mutex (16,33554432,512,16)
68 | 2.88, 19.64, 18.18, ema::shared_mutex (16,33554432,256,16)
69 | 17.45, 24.63,242.72, std::mutex (16,33554432,256,16)
70 | 4.39, 32.54, 26.16, ema::shared_mutex (16,33554432,128,16)
71 | 19.40, 26.51,269.83, std::mutex (16,33554432,128,16)
72 | 20.21,209.27, 88.88, ema::shared_mutex (16,33554432,16,16)
73 | 32.93, 43.14,453.16, std::mutex (16,33554432,16,16)
74 | 73.96,819.51,312.90, ema::shared_mutex (16,33554432,4,16)
75 | 33.63, 43.01,462.74, std::mutex (16,33554432,4,16)
76 | ```
77 | Clearly shows where this type of mutex excels (low write/high read frequency).
78 |
79 | ## How do I include in my project(s)?
80 | Feel free to copy the file `shared_mutex.h` and include it wherever needed; see [license](#license).
81 |
82 | ## How do I use it in my code?
83 | After including the libray, one can use the utility classes `ema::x_lock` and `ema::s_lock` for a nifty RAII e*X*clusive and *S*hared lock respectively. As example:
84 | ``` c++
85 | ema::shared_mutex<4> sm;
86 | if(write_access) {
87 | ema::x_lock<4> lock(sm);
88 | // do your R/W stuff here
89 | }
90 | //
91 | if(read_access) {
92 | ema::s_lock<4> lock(sm);
93 | // do your R/O stuff her
94 | }
95 | ```
96 |
97 | ### What is this class a template?
98 | I could make this class a stadard class (i.e. no template) but being a template allows specifying how many buckets (i.e. the argument to the template) at compile them, thus allowing for compilte time loop unrolling in case the compiler feels to be particularly frisky.
99 |
100 | In all honesty, this template can be easily adapted to be a standard class and the number of buckets to be passed at *run-time*. It's a trivial exercise left to the reader :-)
101 |
102 | ## F.A.Q.s
103 |
104 | ### Why should I use this instead of `std::mutex`?
105 | Run the main (settings optimized for a 4 real cores CPUs) and see the difference between a `std::mutex` and `ema::shared_mutex`. In case you have some writes but many, many __fast__ parallel reads, then `ema::shared_mutex` would provide a huge difference.
106 |
107 | ### Is it better than `boost::shared_mutex`?
108 | Not sure, haven't tested it yet - but in general depends very much on the implementation.
109 | Emphasys of `ema::shared_mutex` implementation is that when a thread needs to access the data in R/O mode, unless there's a writer, then the access will be __virtually__ cost free: there is not going to be __any__ cache contention between threads/CPU cores.
110 |
111 | ### Is it better than `std::shared_mutex`?
112 | See previous Q and A.
113 |
114 | ### When shouldn't I use `ema::shared_mutex`?
115 | If your R/W access blocks for *some time*, then it's much better to go back to `std::mutex`: in this case the R/O (or other R/W) will just spin and burn CPU resources.
116 | The same applies if you have many writers which again do block for some time: the more the writers (and CPU cycles they block), the better `std::mutex` is.
117 |
118 | ### Is it fully tested? Can I use it in my projects?
119 | I have been testing it for a while and seems stable; if you want to use it in your projects, please do perform extensive testing. Again I'm not responsible if it breaks your projects...
120 |
121 | ### Why did you write this?
122 | I was wondering how complex would it be to write something like this from scratch, so I started and possibly produced a *decent prototype*
123 |
124 | ## License
125 | This software is licensed under the LGPLv3, so you can include the header in your source code and just say thanks - no need to release your sources (unless you modify the template that is).
126 |
--------------------------------------------------------------------------------
/src/main.cpp:
--------------------------------------------------------------------------------
1 | /*
2 | * shared_mutex (C) 2017 E. Oriani, ema fastwebnet it
3 | *
4 | * This file is part of shared_mutex.
5 | *
6 | * shared_mutex is free software: you can redistribute it and/or modify
7 | * it under the terms of the GNU Lesser General Public License as published by
8 | * the Free Software Foundation, either version 3 of the License, or
9 | * (at your option) any later version.
10 | *
11 | * shared_mutex is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU General Public License
17 | * along with nettop. If not, see .
18 | */
19 |
20 | #include
21 | #include
22 | #include
23 | #include
24 | #include
25 | #include
26 | #include "shared_mutex.h"
27 |
28 | #define N_BUCKETS 4
29 |
30 | namespace microbench {
31 | struct clocks {
32 | double real,
33 | user,
34 | sys;
35 |
36 | clocks() : real(.0), user(.0), sys(.0) {
37 | }
38 | };
39 |
40 | class proc_timer {
41 | clocks& c_;
42 | struct rusage s_;
43 | struct timeval st_;
44 | public:
45 | proc_timer(clocks& c) : c_(c) {
46 | if(gettimeofday(&st_, NULL)) throw std::runtime_error("gettimeofday error");
47 | if(getrusage(RUSAGE_SELF, &s_)) throw std::runtime_error("getrusage error");
48 | }
49 |
50 | ~proc_timer() {
51 | struct rusage e;
52 | struct timeval et;
53 | if(gettimeofday(&et, NULL)) throw std::runtime_error("gettimeofday error");
54 | if(getrusage(RUSAGE_SELF, &e)) throw std::runtime_error("getrusage error");
55 |
56 | auto f_tv2d = [](const timeval& t, const timeval& f) -> double { return 1.0*(t.tv_sec-f.tv_sec)+1e-6*(t.tv_usec-f.tv_usec); };
57 | const double real = f_tv2d(et, st_),
58 | user = f_tv2d(e.ru_utime, s_.ru_utime),
59 | sys = f_tv2d(e.ru_stime, s_.ru_stime);
60 | c_.real += real;
61 | c_.user += user;
62 | c_.sys += sys;
63 | }
64 | };
65 |
66 | void RW_test(const std::string& label, std::function w_func, std::function r_func, const size_t n_threads, const size_t n_iters, const size_t w_freq, const size_t n_writers) {
67 | clocks c;
68 | {
69 | proc_timer _pt(c);
70 | // test
71 | std::list th_list;
72 | for(size_t i = 0; i < n_threads; ++i) {
73 | th_list.push_back(
74 | std::thread( [&](const bool writer) -> void {
75 | for(size_t j = 0; j < n_iters; ++j) {
76 | if(writer && ((j%w_freq) == 0)){
77 | w_func();
78 | } else {
79 | r_func();
80 | }
81 | }
82 | },
83 | i < n_writers
84 | )
85 | );
86 | }
87 | // wait for threads
88 | for(auto& i : th_list)
89 | i.join();
90 | }
91 | // some stats...
92 | std::printf("%6.2f,%6.2f,%6.2f,%24s\t(%lu,%lu,%lu,%lu)\n", c.real, c.user, c.sys, label.c_str(), n_threads, n_iters, w_freq, n_writers);
93 | }
94 | }
95 |
96 | int main(int argc, char *argv[]) {
97 | try {
98 | ema::shared_mutex sm;
99 | std::mutex mtx;
100 | //
101 | size_t a = 0,
102 | b = 0;
103 |
104 | // increase frequency of writing
105 | size_t w_freq_arr[] = {1024, 512, 256, 128, 16, 4};
106 | std::printf("%6s,%6s,%6s,%24s\n", "real", "user", "sys", "mutex_type");
107 | for(size_t i = 0; i < sizeof(w_freq_arr)/sizeof(size_t); ++i) {
108 | microbench::RW_test(
109 | "ema::shared_mutex",
110 | [&]() { ema::x_lock l_(sm); ++a; ++b; },
111 | [&]() { ema::s_lock l_(sm); if(a != b) throw std::runtime_error("Fail in test!"); },
112 | N_BUCKETS,
113 | 32*1024*1024,
114 | w_freq_arr[i],
115 | N_BUCKETS
116 | );
117 | microbench::RW_test(
118 | "std::mutex",
119 | [&]() { std::lock_guard l_(mtx); ++a; ++b; },
120 | [&]() { std::lock_guard l_(mtx); if(a != b) throw std::runtime_error("Fail in test!"); },
121 | N_BUCKETS,
122 | 32*1024*1024,
123 | w_freq_arr[i],
124 | N_BUCKETS
125 | );
126 | }
127 | } catch(const std::exception& e) {
128 | std::cerr << "Exception: " << e.what() << std::endl;
129 | } catch(...) {
130 | std::cerr << "Unknown exception" << std::endl;
131 | }
132 | }
133 |
134 |
--------------------------------------------------------------------------------
/src/shared_mutex.h:
--------------------------------------------------------------------------------
1 | /*
2 | * shared_mutex (C) 2017 E. Oriani, ema fastwebnet it
3 | *
4 | * This file is part of shared_mutex.
5 | *
6 | * shared_mutex is free software: you can redistribute it and/or modify
7 | * it under the terms of the GNU Lesser General Public License as published by
8 | * the Free Software Foundation, either version 3 of the License, or
9 | * (at your option) any later version.
10 | *
11 | * shared_mutex is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU General Public License
17 | * along with nettop. If not, see .
18 | */
19 |
20 | #ifndef _SHARED_MUTEX_H_
21 | #define _SHARED_MUTEX_H_
22 |
23 | #include
24 | #include
25 | #include
26 |
27 | // this should be defined in the Makefile
28 | // if not defined, use what is most common
29 | // for x86_64 CPUs in 2017...
30 | #ifndef LEVEL1_DCACHE_LINESIZE
31 | #define LEVEL1_DCACHE_LINESIZE 64
32 | #endif
33 |
34 | namespace ema {
35 | template
36 | class shared_mutex {
37 | // purpose of this structure is to hold
38 | // status of each individual bucket-mutex
39 | // object
40 | // Ideally each thread should be mapped to
41 | // one entry only of 'el_' during its
42 | // lifetime
43 | struct entry_lock {
44 | const static uint64_t W_MASK = 0x8000000000000000,
45 | R_MASK = ~W_MASK;
46 |
47 | // purpose ot this variable is to hold
48 | // in the first bit (W_MASK) if we're locking
49 | // in exclusive mode, otherwise use the
50 | // reamining 63 bits to count how many R/O
51 | // locks we share in this very bucket
52 | std::atomic wr_lock;
53 |
54 | entry_lock() : wr_lock(0) {
55 | }
56 | } __attribute__((aligned(LEVEL1_DCACHE_LINESIZE)));
57 | // array holding all the buckets
58 | std::array el_;
59 | // atomic variable used to initialize thread
60 | // ids so that they should evenly spread
61 | // across all the buckets
62 | static std::atomic idx_hint_;
63 | // lock-free function to return a 'unique' id
64 | static uint64_t get_hint_idx(void) {
65 | while(true) {
66 | size_t cur_hint = idx_hint_.load();
67 | if(idx_hint_.compare_exchange_weak(cur_hint, cur_hint+1))
68 | return cur_hint;
69 | }
70 | }
71 | // get index for given thread
72 | // could hav used something like std::hash()(std::this_thread::get_id())
73 | // but honestly using a controlled idx_hint_
74 | // seems to be better in terms of putting threads
75 | // into buckets evenly
76 | // note - thread_local is supposed to be static...
77 | inline static size_t get_thread_idx(void) {
78 | const thread_local size_t rv = get_hint_idx()%N;
79 | return rv;
80 | }
81 | public:
82 | shared_mutex() {
83 | }
84 |
85 | void lock_shared(void) {
86 | // try to replace the wr_lock with current value incremented by one
87 | while(true) {
88 | size_t cur_rw_lock = el_[get_thread_idx()].wr_lock.load();
89 | if(entry_lock::W_MASK & cur_rw_lock) {
90 | // if someone has got W access yield and retry...
91 | std::this_thread::yield();
92 | continue;
93 | }
94 | if(el_[get_thread_idx()].wr_lock.compare_exchange_weak(cur_rw_lock, cur_rw_lock+1))
95 | break;
96 | }
97 | }
98 |
99 | void unlock_shared(void) {
100 | // try to decrement the count
101 | while(true) {
102 | size_t cur_rw_lock = el_[get_thread_idx()].wr_lock.load();
103 | #ifndef _RELEASE
104 | if(entry_lock::W_MASK & cur_rw_lock)
105 | throw std::runtime_error("Fatal: unlock_shared but apparently this entry is W_MASK locked!");
106 | #endif //_RELEASE
107 | if(el_[get_thread_idx()].wr_lock.compare_exchange_weak(cur_rw_lock, cur_rw_lock-1))
108 | break;
109 | }
110 | }
111 |
112 | void lock(void) {
113 | for(size_t i = 0; i < N; ++i) {
114 | // acquire all locks from all buckets
115 | while(true) {
116 | size_t cur_rw_lock = el_[i].wr_lock.load();
117 | if(cur_rw_lock != 0) {
118 | std::this_thread::yield();
119 | continue;
120 | }
121 | // if cur_rw_lock is 0 then proceed
122 | if(el_[i].wr_lock.compare_exchange_weak(cur_rw_lock, entry_lock::W_MASK))
123 | break;
124 | }
125 | }
126 | }
127 |
128 | void unlock(void) {
129 | for(size_t i = 0; i < N; ++i) {
130 | // release all locks
131 | while(true) {
132 | size_t cur_rw_lock = el_[i].wr_lock.load();
133 | #ifndef _RELEASE
134 | if(cur_rw_lock != entry_lock::W_MASK)
135 | throw std::runtime_error("Fatal: unlock but apparently this entry is shared locked or uninitialized!");
136 | #endif //_RELEASE
137 | // then proceed resetting to 0
138 | if(el_[i].wr_lock.compare_exchange_weak(cur_rw_lock, 0))
139 | break;
140 | }
141 | }
142 | }
143 |
144 | ~shared_mutex() {
145 | }
146 | };
147 |
148 | template
149 | std::atomic shared_mutex::idx_hint_{0};
150 |
151 | // utility class for exclusive RAII lock
152 | template
153 | class x_lock {
154 | shared_mutex& sm_;
155 | public:
156 | x_lock(shared_mutex& sm) : sm_(sm) {
157 | sm_.lock();
158 | }
159 |
160 | ~x_lock() {
161 | sm_.unlock();
162 | }
163 | };
164 |
165 | // utility class for share RAII lock
166 | template
167 | class s_lock {
168 | shared_mutex& sm_;
169 | public:
170 | s_lock(shared_mutex& sm) : sm_(sm) {
171 | sm_.lock_shared();
172 | }
173 |
174 | ~s_lock() {
175 | sm_.unlock_shared();
176 | }
177 | };
178 | }
179 |
180 | #endif //_SHARED_MUTEX_H_
181 |
182 |
--------------------------------------------------------------------------------