美文网首页
通过原子类型atomic_flag实现自旋锁spinlock

通过原子类型atomic_flag实现自旋锁spinlock

作者: 薛定谔的柴猫 | 来源:发表于2021-11-07 17:11 被阅读0次

原理

std::atomic_flag的方法test_and_set()是原子的。flag为false时, test_and_set()将flag置为true并返回false; flag为true时, test_and_set()将返回true。

代码实现

#include <pthread.h>
#include <atomic>
#include <iostream>
using namespace std;

int total = 0;

class spinLock {
private:
    atomic_flag flag;

public:
    spinLock(){};
    void lock() {
        while (flag.test_and_set()) ;
    }

    void unlock() {
        flag.clear();
    }
};

void *taskFunc(void* arg)
{
    auto spin = (spinLock *)arg;
    while (total < 10) {
        spin->lock();
        cout << "number:" << total << "; thread:" << pthread_self() << endl;
        total++;
        spin->unlock();
    }
    return NULL;
}

int main()
{
    pthread_t pthid1, pthid2;
    spinLock spin;
    pthread_create(&pthid1, NULL, taskFunc, (void *)&spin);
    pthread_create(&pthid2, NULL, taskFunc, (void *)&spin);
    pthread_join(pthid1, NULL);
    pthread_join(pthid2, NULL);
    return 0;
}

测试结果

> g++ -o testspinlock testspinlock.cpp
> ./testspinlock
number:0; thread:0x70000afba000
number:1; thread:0x70000b03d000
number:2; thread:0x70000b03d000
number:3; thread:0x70000b03d000
number:4; thread:0x70000b03d000
number:5; thread:0x70000b03d000
number:6; thread:0x70000b03d000
number:7; thread:0x70000afba000
number:8; thread:0x70000afba000
number:9; thread:0x70000afba000
number:10; thread:0x70000b03d000

相关文章

网友评论

      本文标题:通过原子类型atomic_flag实现自旋锁spinlock

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