美文网首页
使用原子操作实现互斥锁

使用原子操作实现互斥锁

作者: zjh3029 | 来源:发表于2020-03-24 18:14 被阅读0次

    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循环并不能实现互斥锁的结构,这就是原子操作的作用
    //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;
    

    }

    相关文章

      网友评论

          本文标题:使用原子操作实现互斥锁

          本文链接:https://www.haomeiwen.com/subject/lprayhtx.html