Skip to content

spinning on an atomic leaks memory when using jemalloc #1347

@amosbird

Description

@amosbird

When keeping spawning new threads doing this spin and exits, process RSS keeps going up and finally gets OOM killed when linking with jemalloc. libc malloc doesn't have this problem.

#include <atomic>
#include <thread>
#include <deque>
#include <chrono>

inline int do_spin(std::atomic<unsigned> & generation, unsigned int val)
{
    for (;;)
        if (generation.load(std::memory_order_relaxed) != val)
            return 0;
}

int main(int argc, char *argv[]) {
    std::atomic<unsigned> generation = 0;
    for(;;) {
        std::deque<std::thread> q;
        for (auto i = 1u; i < 40; ++i) {
            q.push_back(std::thread([&]() {
                do_spin(generation, generation);
            }));
        }
        using namespace std::chrono_literals;
        std::this_thread::sleep_for(100ms);
        generation ++;
        for (auto & t : q) {
            t.join();
        }
    }
}

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions