ostatnia linia w funkcji push powoduje błąd nr. C2665
plik main.cpp
#include <iostream>
#include <thread>
//#include "lock_free_stack.h"
#include "shared_ptr_stack20.h"
//#include "hazard_pointers_stack.h"
using namespace std;
shared_ptr_stack20<int> temp;
void add_function() {
for (int i = 0; i < 500000; i++) {
temp.push(i);
}
}
void pop_function() {
for (int i = 0; i < 500000; i++) {
temp.pop();
}
}
int main()
{
thread t1(add_function);
thread t2(add_function);
t1.join();
t2.join();
thread t3(pop_function);
thread t4(pop_function);
t3.join();
t4.join();
shared_ptr<int> t;
if (!temp.pop())
cout << "udalo_sie" << endl;
else
cout << "nie udalo sie" << endl;
}
plik shared_ptr_stack20.h
#pragma once
#include <atomic>
#include <memory>
template <typename T>
class shared_ptr_stack20 {
private:
struct node {
std::shared_ptr<T> data;
std::atomic<std::shared_ptr<node>> next;
node(const T& data_) :data(std::make_shared<T>(data_)) {
}
};
std::atomic<std::shared_ptr<node>> head;
public:
std::shared_ptr<T> pop() {
std::shared_ptr<node> old_head = head.load();
while (old_head && !head.compare_exchange_weak(old_head, old_head->next.load()));
if (old_head) {
old_head->next.store(std::shared_ptr<node>());
return old_head->data;
}
return std::shared_ptr<T>();
}
void push(const T& value) {
std::shared_ptr<node> temp = std::make_shared<node>(value);
temp->next = head.load();
while (!head.compare_exchange_weak(temp->next, temp);
}
~shared_ptr_stack20() {
while (pop());
}
};