使用事务性内存时出现段错误,尝试实现golang的chan类

时间:2019-01-29 08:10:30

标签: c++

我的代码紧随其后,逻辑是可读的,我不确定原子的代码,即使没有警告也可以编译,但我一次又一次遇到段错误

#include <atomic>
//#include <mutex>
#include <memory>
//#include <math.h>
//#include <optional>
#include <utility>

using namespace std;

namespace tema2 {
template <class T,size_t A>
class fl_chan {
public:
    fl_chan(){
        //long unsigned int zero = 0;
        place_st.store(0);
        take_st.store(0);
        delta.store(0);
        return;
    };
    bool recv(T &trg){
        synchronized {
            synchronized {
                if (take_st == A){
                    take_st.store(0);
                }
            }
            if (delta == 0){
                return false;
            }

            T var = T();
            swap(var,data[take_st++]);
            trg = var;
            --delta;
            return true;
        }
    }
    bool send(T arg){
        synchronized {
            synchronized {
                if (place_st == A){
                    place_st.store(0);
                }
            }
            data[place_st++]=arg;
            ++delta;
            return true;
        }
    }

private:
    T data[A];
    atomic<uint64_t> place_st;
    atomic<uint64_t> take_st;
    atomic<uint64_t> delta;
};


};

0 个答案:

没有答案