Created
June 27, 2018 23:42
-
-
Save nelhage/cb90d8457aff3d0b860520d6ea6c6e5c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <thread> | |
#include <experimental/optional> | |
#include <atomic> | |
#include <shared_mutex> | |
#include <mutex> | |
#include <iostream> | |
#include <vector> | |
using namespace std; | |
class LogConstruction { | |
public: | |
LogConstruction() { | |
constructions.fetch_add(1); | |
} | |
~LogConstruction() { | |
destructions.fetch_add(1); | |
} | |
static atomic<int> constructions; | |
static atomic<int> destructions; | |
}; | |
atomic<int> LogConstruction::constructions{0}; | |
atomic<int> LogConstruction::destructions{0}; | |
std::experimental::optional<LogConstruction> value; | |
shared_mutex mtx; | |
atomic<bool> shutdown = false; | |
void worker() { | |
while(true) { | |
shared_lock<shared_mutex> lock(mtx); | |
if (shutdown) { | |
return; | |
} | |
if (!value) { | |
value.emplace(); | |
} | |
} | |
} | |
const int kThreads = 4; | |
const int kLoops = 1000000; | |
int main() { | |
vector<thread> threads; | |
for (int i = 0; i < kThreads; ++i) { | |
threads.emplace_back(worker); | |
} | |
for (int i = 0; i < kLoops; ++i) { | |
unique_lock<shared_mutex> lk(mtx); | |
value = std::experimental::optional<LogConstruction>(); | |
} | |
{ | |
unique_lock<shared_mutex> lk(mtx); | |
shutdown = true; | |
} | |
for (auto &th : threads) { | |
th.join(); | |
} | |
cout << "constructions=" << LogConstruction::constructions << endl; | |
cout << " destructions=" << LogConstruction::destructions << endl; | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment