define _CRT_SECURE_NO_WARNINGS
include <iostream>
include <thread>
include <Windows.h>
include <atomic>
using namespace std;
typedef int Mutex;
Mutex Lock_read = 0;
Mutex Lock_write = 0;
string sTeststr = "test";
std::atomic_flag alock = ATOMIC_FLAG_INIT;
void Locked(Mutex &mutextype)
{
while (true == alock.test_and_set()) {}
//while (mutextype == 1) {}; //使用while循環(huán)并不能實現互斥鎖的結構灵奖,這就是原子操作的作用
//mutextype = 1;
}
void Unlock(Mutex& mutextype)
{
alock.clear();
//mutextype = 0;
}
void testLock(string sInput)
{
Locked(Lock_write);
sTeststr = sInput;
cout << sTeststr << "=" << sInput<<"mutex:"<< Lock_write << endl;
Unlock(Lock_write);
}
int main()
{
thread thread1(testLock, "1");
thread thread2(testLock, "2");
thread thread3(testLock, "3");
thread thread4(testLock, "4");
thread1.join();
thread2.join();
thread3.join();
thread4.join();
return 0;
}