반응형

 

shared_ptr 을 사용 하면서 atomic 으로 처리 되게 하며녀 

 

shared_ptr<Node> _head;

 

shared_ptr<Node> oldHead = std::atomic_load(&_head);

이렇게 다른 shared 변수에 대입 또는 

 

auto localPtr = ....;

shared_ptr oldHead = std::atomic_load(&_head, localPtr);

 

이런 식으로 처리 할 수 있다

이것을 이용해 lockFree stack 을 구현해 본다면 다음과 같은 형태로 될것인데..

template<typename T>
class LockFreeStack
{
	struct Node
	{
		Node(const T& value) : data(make_shared<T>(value)), next(nullptr)
		{

		}

		shared_ptr<T> data;
		shared_ptr<Node> next;
	};

public:
	void Push(const T& value)
	{
		shared_ptr<Node> node = make_shared<Node>(value);
		node->next = std::atomic_load(&_head);
		while (std::atomic_compare_exchange_weak(&_head, &node->next, node) == false)
		{
		}
	}

	shared_ptr<T> TryPop()
	{
		shared_ptr<Node> oldHead = std::atomic_load(&_head);

		while (oldHead && std::atomic_compare_exchange_weak(&_head, &oldHead, oldHead->next) == false)
		{

		}

		if (oldHead == nullptr)
			return shared_ptr<T>();

		return oldHead->data;
	}

private:
	shared_ptr<Node> _head;
};

 

 

문제는 shaed_ptr 자체가 lock free 가 아니다 보니
https://3dmpengines.tistory.com/2210 참고
이렇게 구현하는건 의미가 없다

 

 

 

반응형

+ Recent posts