File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 77
88#include < vector>
99#include < stdexcept>
10+ #include < thread>
1011
1112#if ISPTR_USE_MODULES
1213 import isptr;
@@ -179,4 +180,42 @@ TEST_CASE( "Ref counted wrapper" ) {
179180 }
180181}
181182
183+ TEST_CASE ( " Atomic" ) {
184+
185+ struct Foo : public ref_counted <Foo> {
186+ int x;
187+ Foo (int v) : x(v) {}
188+ };
189+
190+ constexpr int N_THREADS = 8 ;
191+ constexpr int N_OPS = 100000 ;
192+ std::atomic<refcnt_ptr<Foo>> shared (make_refcnt<Foo>(0 ));
193+
194+ std::vector<std::thread> threads;
195+ std::atomic<int > errors{0 };
196+
197+ for (int i = 0 ; i < N_THREADS; ++i) {
198+ threads.emplace_back ([&shared, i, &errors]{
199+ for (int j = 0 ; j < N_OPS; ++j) {
200+ if ((j & 1 ) == 0 ) {
201+ auto v = shared.load ();
202+ if (v && v->x < 0 ) errors.fetch_add (1 );
203+ } else {
204+ shared.store (make_refcnt<Foo>(i * N_OPS + j));
205+ }
206+ }
207+ });
208+ }
209+ for (auto & t : threads) t.join ();
210+ CHECK (errors.load () == 0 );
211+ auto val = shared.load ()->x ;
212+ INFO (val);
213+ auto i = val / N_OPS;
214+ CHECK (i >= 0 );
215+ CHECK (i < N_THREADS);
216+ auto j = val % N_OPS;
217+ CHECK (j >= 0 );
218+ CHECK (j < N_OPS);
219+ }
220+
182221}
You can’t perform that action at this time.
0 commit comments