2 * Copyright 2016 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
19 #include <folly/AtomicIntrusiveLinkedList.h>
20 #include <folly/Memory.h>
25 * A very simple atomic single-linked list primitive.
29 * AtomicLinkedList<MyClass> list;
31 * list.sweep([] (MyClass& c) { doSomething(c); }
35 class AtomicLinkedList {
38 AtomicLinkedList(const AtomicLinkedList&) = delete;
39 AtomicLinkedList& operator=(const AtomicLinkedList&) = delete;
40 AtomicLinkedList(AtomicLinkedList&& other) noexcept = default;
41 AtomicLinkedList& operator=(AtomicLinkedList&& other) = default;
52 * Atomically insert t at the head of the list.
53 * @return True if the inserted element is the only one in the list
56 bool insertHead(T t) {
57 auto wrapper = folly::make_unique<Wrapper>(std::move(t));
59 return list_.insertHead(wrapper.release());
63 * Repeatedly pops element from head,
64 * and calls func() on the removed elements in the order from tail to head.
65 * Stops when the list is empty.
68 void sweep(F&& func) {
69 list_.sweep([&](Wrapper* wrapperPtr) mutable {
70 std::unique_ptr<Wrapper> wrapper(wrapperPtr);
72 func(std::move(wrapper->data));
78 explicit Wrapper(T&& t) : data(std::move(t)) {}
80 AtomicIntrusiveLinkedListHook<Wrapper> hook;
83 AtomicIntrusiveLinkedList<Wrapper, &Wrapper::hook> list_;