Designing lock-free parallel BFS in C++
I'm preparing a C++17 implementation of parallel BFS using a frontier-based approach with multiple threads processing slices of the frontier. The key is an atomic bitset with a test-and-set method using compare_exchange to mark visited nodes without locks, and thread-local next-frontier vectors merged after threads join.
Below is a minimal C++17 example of a frontier‑based parallel BFS that uses a shared atomic bitset to mark visited vertices without locks. Each BFS “level” is processed in parallel by a fixed set of worker threads; they split the current frontier into contiguous chunks, generate per‑thread “next frontier” vectors, and merge those vectors after the threads join.
#include <atomic>
#include <cstdint>
#include <iostream>
#include <thread>
#include <vector>
// A simple adjacency list graph.
struct Graph {
std::vector<std::vector<int>> adj;
};
// Atomic bitset for lock‑free test‑and‑set of visited flags.
class AtomicBitset {
public:
explicit AtomicBitset(std::size_t n_bits) {
std::size_t n_words = (n_bits + 63) / 64;
bits_.resize(n_words);
for (auto &b : bits_) {
b.store(0, std::memory_order_relaxed);
}
}
// Returns true if we successfully set the bit (i.e., it was not set before).
bool try_mark(std::size_t idx) {
std::size_t word_idx = idx / 64;
std::size_t bit_pos = idx % 64;
uint64_t mask = uint64_t{1} << bit_pos;
// Loop until we either set the bit or discover it's already set.
uint64_t old = bits_[word_idx].load(std::memory_order_relaxed);
while ((old & mask) == 0) {
if (bits_[word_idx].compare_exchange_weak(
old, old | mask,
std::memory_order_acq_rel,
std::memory_order_relaxed)) {
return true; // we set it
}
// If compare_exchange_weak failed spuriously or because old changed,
// it updates 'old' with the current value; loop continues.
}
return false; // already set
}
bool is_marked(std::size_t idx) const {
std::size_t word_idx = idx / 64;
std::size_t bit_pos = idx % 64;
uint64_t mask = uint64_t{1} << bit_pos;
return (bits_[word_idx].load(std::memory_order_relaxed) & mask) != 0;
}
private:
std::vector<std::atomic<uint64_t>> bits_;
};
// Parallel BFS with a fixed number of threads.
std::vector<int> parallel_bfs(const Graph &g, int source, int num_threads) {
const int n = static_cast<int>(g.adj.size());
std::vector<int> distance(n, -1);
AtomicBitset visited(n);
// Initialize frontier with the source.
visited.try_mark(source);
distance[source] = 0;
std::vector<int> frontier = {source};
int depth = 0;
while (!frontier.empty()) {
// Prepare per‑thread next frontiers to avoid contention when pushing.
std::vector<std::vector<int>> thread_frontiers(num_threads);
// Worker lambda to process a slice of the current frontier.
auto worker = [&](int tid) {
int fsize = static_cast<int>(frontier.size());
int start = (tid * fsize) / num_threads;
int end = ((tid + 1) * fsize) / num_threads;
auto &local_next = thread_frontiers[tid];
for (int i = start; i < end; ++i) {
int u = frontier[i];
for (int v : g.adj[u]) {
if (visited.try_mark(v)) {
distance[v] = depth + 1;
local_next.push_back(v);
}
}
}
};
// Launch threads.
std::vector<std::thread> threads;
threads.reserve(num_threads);
for (int t = 0; t < num_threads; ++t) {
threads.emplace_back(worker, t);
}
for (auto &thr : threads) {
thr.join();
}
// Merge per‑thread next frontiers.
std::vector<int> next_frontier;
for (const auto &local : thread_frontiers) {
next_frontier.insert(next_frontier.end(), local.begin(), local.end());
}
frontier.swap(next_frontier);
++depth;
}
return distance;
}
// Example usage
int main() {
// Build a simple undirected graph.
Graph g;
g.adj.resize(6);
auto add_edge = [&](int u, int v) {
g.adj[u].push_back(v);
g.adj[v].push_back(u);
};
add_edge(0, 1);
add_edge(0, 2);
add_edge(1, 3);
add_edge(1, 4);
add_edge(2, 4);
add_edge(3, 5);
add_edge(4, 5);
int num_threads = 4;
auto dist = parallel_bfs(g, /*source=*/0, num_threads);
std::cout << "Distances from node 0:\n";
for (int i = 0; i < static_cast<int>(dist.size()); ++i) {
std::cout << "Node " << i << ": " << dist[i] << "\n";
}
return 0;
}
Key points:
AtomicBitset::try_mark uses a compare_exchange_weak loop to test and set the appropriate bit without locks. It returns true only when it successfully sets a previously clear bit.
- Each BFS level is processed by
num_threads worker threads. They read the shared frontier (which is not modified during the level) and append new vertices to a thread‑local local_next.
- After all threads complete, the per‑thread next frontiers are concatenated to form the new frontier.
- The shared
distance vector is only written for newly discovered vertices, immediately after successfully marking them visited.