Last active
March 19, 2018 16:10
-
-
Save LYP951018/36146c4eb3b0cef8cc526ef9e9543e3d 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 <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