Skip to content

Instantly share code, notes, and snippets.

@LYP951018
Last active March 19, 2018 16:10
Show Gist options
  • Save LYP951018/36146c4eb3b0cef8cc526ef9e9543e3d to your computer and use it in GitHub Desktop.
Save LYP951018/36146c4eb3b0cef8cc526ef9e9543e3d to your computer and use it in GitHub Desktop.
#include <cstdint>
#include <Windows.h>
#include <cassert>
#include <thread>
#include <iostream>
struct Mutex
{
public:
void lock()
{
const auto currentId = ::GetCurrentThreadId();
unsigned long expectedOwner = 0;
while (true)
{
if (::InterlockedCompareExchange(&owner_, currentId, 0) != 0)
{
::WaitOnAddress(&owner_, &expectedOwner, sizeof(unsigned long), INFINITE);
}
else break;
}
}
void unlock()
{
const auto currentId = ::GetCurrentThreadId();
assert(owner_ == currentId);
InterlockedExchange(&owner_, 0);
WakeByAddressSingle(&owner_);
}
private:
unsigned long owner_{};
};
Mutex lock;
void Output()
{
for (int i = 0; i < 10000; ++i)
{
lock.lock();
std::cout << i << ' ';
std::cout.flush();
lock.unlock();
}
}
int main()
{
std::thread th1{ Output };
std::thread th2{ Output };
th1.detach();
th2.join();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment