Skip to content

Instantly share code, notes, and snippets.

@wheybags
Last active August 19, 2017 17:33
Show Gist options
  • Save wheybags/bde2edb72151b0e40e818dab98f76a81 to your computer and use it in GitHub Desktop.
Save wheybags/bde2edb72151b0e40e818dab98f76a81 to your computer and use it in GitHub Desktop.
#include <thread>
#include <mutex>
#include <atomic>
class State
{
public:
std::mutex mMutex;
};
std::atomic<State*> curr;
std::atomic<int> threadState;
void loop()
{
threadState = 1;
while(threadState != 2)
{
State* current = curr;
if(current && current->mMutex.try_lock())
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
current->mMutex.unlock();
}
}
}
State states[3];
State* getFreeState()
{
while(true)
{
for(size_t i = 0; i < 3; i++)
{
if(&states[i] != curr && states[i].mMutex.try_lock())
{
return &states[i];
}
}
}
return NULL;
}
void setCurrent(State* current)
{
current->mMutex.unlock();
curr = current;
}
int main(int argc, char** argv)
{
// initialisation
curr = nullptr;
threadState = 0;
std::thread t(loop);
while(threadState != 1)
std::this_thread::yield();
for(size_t i = 0; i < 100; i++)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
State* s = getFreeState();
setCurrent(s);
}
threadState = 2;
t.join();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment