美文网首页
c++ atomic 乐观锁实现CountDownload

c++ atomic 乐观锁实现CountDownload

作者: 贼噶人 | 来源:发表于2020-01-12 20:09 被阅读0次
  
#include<atomic>
#include<thread>
class CountDownload{
    private:
        std::atomic<int> number;
    public:
        CountDownload(int num);
        void await();
        void dwonload();
};

CountDownload::CountDownload(int num){
    number.exchange(num);
}

void CountDownload::await(){
    while(number > 0){
        std::this_thread::yield();
    }
}

void CountDownload::dwonload(){
    number--;
}

#include<iostream>
#include<atomic>
#include<thread>
#include<vector>
#include<pthread.h>
#include<mutex>
#include"CountDwonload.cpp"

using namespace std;

std::atomic<bool> reay(false);
std::atomic<int> number(0);
std::atomic<bool> winner(false);
std::mutex mymutex;
CountDownload mCountDownload(10);

void* hello(void* id){
    while(!reay){

    }
    for (size_t i = 0; i < 10000000; i++)
    {
        /* code */
    }
    std::cout << "结束!" << *((int *) id) << std::endl;
    mCountDownload.dwonload();
    free(id);
    return NULL;
}

int main(int argv,char ** argc){
    pthread_t threads[10];
    for (size_t i = 0; i < 10; i++)
    {
        int* m = (int *)calloc(1,sizeof(int));
        *m = i;
        pthread_create(&threads[i],NULL,hello,m);
    }
    reay = true;
    mCountDownload.await();
    std::cout << "结束!" << std::endl;
    return 0;
}
gangzhoudeAir:~ gang.zhou$  ./Hello 
结束!3
结束!6
结束!7
结束!0
结束!5
结束!4
结束!2
结束!1
结束!8
结束!9
结束!
gangzhoudeAir:~ gang.zhou$ 

相关文章

网友评论

      本文标题:c++ atomic 乐观锁实现CountDownload

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