Skip to content
binshelf/ cpp

Search lessons

Type a C++ term, like vector, reference, unique_ptr or use-after-free.

    Lessons

    On this page

    1. Key terms
    2. In 30 seconds
    3. One count table per thread
    4. Printing in a fixed order
    5. Why not one shared map?
    6. A reader thread and a work queue
    7. Parallel algorithms for per-read work
    8. Measuring the speedup
    9. Which one should I use?
    10. Under the hood
    11. Common pitfalls
    12. A shared progress counter
    13. Merging with = instead of +=
    14. Holding a view into a line that changes
    15. Try it yourself

    Module 12 · C++ for bioinformatics

    12.4Processing reads in parallel

    Count k-mers in many reads on every core: split the reads among std::jthreads, give each thread its own counts and merge them at the end, feed workers from a reader thread through a queue, use parallel algorithms for per-read work, measure the speedup and keep the output the same every run.

    About 30 minutesAdvanced

    On this page
    1. Key terms
    2. In 30 seconds
    3. One count table per thread
    4. Printing in a fixed order
    5. Why not one shared map?
    6. A reader thread and a work queue
    7. Parallel algorithms for per-read work
    8. Measuring the speedup
    9. Which one should I use?
    10. Under the hood
    11. Common pitfalls
    12. A shared progress counter
    13. Merging with = instead of +=
    14. Holding a view into a line that changes
    15. Try it yourself

    Key terms

    per-thread counts
    A separate count table for each thread. Each thread writes only its own, so no locks are needed while counting.
    merge
    Combine several count tables into one by adding up the counts for each key.
    strided split
    Thread t of n takes items t, t + n, t + 2n and so on, so long and short reads spread evenly over the threads.
    load balancing
    Giving every thread about the same amount of work, so none sits idle while another finishes.
    work queue
    A queue, safe to use from several threads, that one thread fills with work and worker threads take work from.
    batch
    A group of reads passed through the queue as one item, so the queue's lock is taken once per batch instead of once per read.
    bounded queue
    A work queue with a size limit. Adding to it waits while it's full, so a fast reader can't fill memory faster than the workers empty it.
    deterministic output
    Output that is the same on every run, however the threads happened to be scheduled.

    A sequencing run gives you millions of reads, and counting their k-mers on one thread leaves most of your cores idle. Reads are independent of each other, so the work splits naturally: hand each thread some of the reads. The catch is the count table. If every thread adds to the same map, they corrupt it. This lesson gives each thread its own counts and merges them at the end, feeds the threads from a reader through a queue, and checks that it really is faster.

    In 30 seconds

    • Split the reads among std::jthreads. Each thread counts into its own map; after the threads finish, merge the maps by adding counts.
    • One map shared by all threads is a data race. ThreadSanitizer catches it; a mutex around every count fixes it but makes the threads take turns.
    • When reads arrive from a file, one reader thread pushes batches of reads into a work queue and the workers take batches from it.
    • Per-read work (GC content, lengths, sorting) fits the parallel algorithms. Sort before printing, so the output is the same every run.

    One count table per thread

    The k-mer codes are the ones from 2-bit DNA and k-mers: each base becomes 2 bits (A = 0, C = 1, G = 2, T = 3), and a rolling code slides along the read. add_kmers counts every k-mer of one read and starts over after an N. count_parallel gives thread t the reads t, t + threads, t + 2 * threads and so on, a strided split: if the long reads are bunched together in the input, they still spread over all the threads.

    #include <algorithm>
    #include <cstdint>
    #include <print>
    #include <string>
    #include <string_view>
    #include <thread>
    #include <unordered_map>
    #include <utility>
    #include <vector>
    
    using Counts = std::unordered_map<std::uint64_t, long long>;
    constexpr int k = 3;
    
    void add_kmers(std::string_view read, Counts& counts) {
        std::uint64_t mask = (std::uint64_t{1} << (2 * k)) - 1;
        std::uint64_t code = 0;
        int valid = 0; // bases since the last N
        for (char base : read) {
            std::size_t bits = std::string_view("ACGT").find(base);
            if (bits == std::string_view::npos) {
                valid = 0;
                continue;
            }
            code = ((code << 2) | bits) & mask;
            if (++valid >= k) {
                ++counts[code];
            }
        }
    }
    
    Counts count_parallel(const std::vector<std::string>& reads,
                          std::size_t threads) {
        std::vector<Counts> per_thread(threads);
        {
            std::vector<std::jthread> workers;
            for (std::size_t t = 0; t < threads; ++t) {
                workers.emplace_back([&reads, &per_thread, t, threads] {
                    for (std::size_t i = t; i < reads.size(); i += threads) {
                        add_kmers(reads[i], per_thread[t]);
                    }
                });
            }
        } // all threads have joined here
        Counts total;
        for (const Counts& counts : per_thread) {
            for (auto [code, n] : counts) {
                total[code] += n;
            }
        }
        return total;
    }
    
    std::string decode(std::uint64_t code) {
        std::string kmer(k, 'A');
        for (int i = k - 1; i >= 0; --i) {
            kmer[i] = "ACGT"[code & 3];
            code >>= 2;
        }
        return kmer;
    }
    
    int main() {
        std::vector<std::string> reads = {"GATTACA", "TTACAGG", "ACAGATTACA",
                                          "GANNACA", "CATTACAGAT"};
        Counts counts = count_parallel(reads, 4);
        std::println("same as one thread: {}", counts == count_parallel(reads, 1));
    
        std::vector<std::pair<std::uint64_t, long long>> sorted(counts.begin(),
                                                                counts.end());
        std::ranges::sort(sorted, [](const auto& a, const auto& b) {
            return a.second != b.second ? a.second > b.second : a.first < b.first;
        });
        for (std::size_t i = 0; i < 4; ++i) {
            std::println("{} {}", decode(sorted[i].first), sorted[i].second);
        }
    }

    Output

    same as one thread: true
    ACA 6
    TAC 4
    TTA 4
    ATT 3

    Each thread writes only per_thread[t], a map no other thread touches, so counting needs no lock at all. The merge runs on one thread after the inner block has joined every worker. It costs one pass over each thread’s map, and a map can’t hold more than 4k different k-mers however many reads went in, so with a few threads the merge is small next to the counting. (The measurement below shows what happens with many.)

    Comparing with the one-thread result is a cheap test worth keeping: whatever the number of threads, integer counts must come out the same.

    Printing in a fixed order

    The end of main copies the counts into a vector of (code, count) pairs and sorts it before printing. That step matters. An std::unordered_map iterates in an order that depends on its hash table, and the order can change when the same keys are inserted in a different order, as happens when threads finish in a different order. The counts are the same every run; without the sort, the order they print in might not be. Here the most frequent k-mers come first, ties are broken by the code (for 2-bit codes, that’s alphabetical order), and decode turns a code back into letters, 2 bits at a time from the right.

    Why not one shared map?

    It’s tempting to let every thread add to one shared map. But ++counts[key] may insert a node and rehash the table, and two threads doing that at once is a data race: undefined behavior that can lose counts or crash. Here two threads count bases, the simplest key there is, into one map, and ThreadSanitizer reports the race:

    #include <cstddef>
    #include <string>
    #include <thread>
    #include <unordered_map>
    #include <vector>
    
    std::vector<std::string> reads = {"GATTACA", "TTACAGG", "ACAGATTACA"};
    std::unordered_map<char, long long> counts; // one map for every thread
    {
        std::vector<std::jthread> workers;
        for (std::size_t t = 0; t < 2; ++t) {
            workers.emplace_back([&reads, &counts, t] {
                for (std::size_t i = t; i < reads.size(); i += 2) {
                    for (char base : reads[i]) {
                        ++counts[base];
                    }
                }
            });
        }
    }

    This fails when it runs

    WARNING: ThreadSanitizer: data race
      Read of size 8 at 0x… by thread T2:
        #0 std::_Hashtable<char, std::pair<char const, long long>, std::allocator<std::pair<char const, long long> >, std::__detail::_Select1st, std::equal_to<char>, std::hash<char>, std::__detail::_Mod_range_hashing, std::__detail::_Default_ranged_hash, std::__detail::_Prime_rehash_policy, std::__detail::_Hashtable_traits<false, false, true> >::_M_bucket_index(unsigned long) const
           … 2 frames inside the standard library
        #3 operator() main.cpp:15
           … 6 frames inside the standard library
    
      Previous write of size 8 at 0x… by thread T1:
        #0 std::_Hashtable<char, std::pair<char const, long long>, std::allocator<std::pair<char const, long long> >, std::__detail::_Select1st, std::equal_to<char>, std::hash<char>, std::__detail::_Mod_range_hashing, std::__detail::_Default_ranged_hash, std::__detail::_Prime_rehash_policy, std::__detail::_Hashtable_traits<false, false, true> >::_M_rehash(unsigned long, std::integral_constant<bool, true>)
           … 3 frames inside the standard library
        #4 operator() main.cpp:15
           … 6 frames inside the standard library
    
      Location is stack of main thread.
    
      Thread T2 (running) created by main thread at:
        #0 pthread_create
           … 2 frames inside the standard library
    
      Thread T1 (finished) created by main thread at:
        #0 pthread_create
           … 2 frames inside the standard library
    
    SUMMARY: ThreadSanitizer: data race main.cpp:15 in operator()

    A std::mutex locked around each ++counts[...] (Mutexes and atomics) removes the race, but then only one thread counts at a time, and the threads spend their time waiting for the lock: usually slower than one thread alone. Per-thread counts need no lock until the merge.

    A reader thread and a work queue

    So far all the reads were in memory before counting started. A real FASTQ file can be bigger than your memory, and reading it (Reading FASTA and FASTQ) takes time too. A better shape: one thread reads, and the workers count while it reads. They meet in a work queue like the one in Mutexes and atomics, changed to carry a batch of reads per item: a std::vector<std::string>. Taking a lock once per read would make the threads fight over the queue; once per batch of a few thousand reads, the lock hardly matters.

    Here the reader is main, reading one sequence per line from standard input, with batches of 2 to keep the example small. add_kmers is the helper from above and merge is the merge loop from count_parallel as a function; both are hidden here to save space, and the Run button includes them:

    #include <condition_variable>
    #include <iostream>
    #include <mutex>
    #include <optional>
    #include <print>
    #include <queue>
    #include <string>
    #include <thread>
    #include <utility>
    #include <vector>
    
    using Batch = std::vector<std::string>;
    
    class BatchQueue {
    public:
        void push(Batch batch) {
            std::scoped_lock lock(mutex_);
            batches_.push(std::move(batch));
            ready_.notify_one();
        }
        void close() {
            std::scoped_lock lock(mutex_);
            closed_ = true;
            ready_.notify_all();
        }
        // Waits for a batch; std::nullopt once closed and empty.
        std::optional<Batch> pop() {
            std::unique_lock lock(mutex_);
            ready_.wait(lock, [this] { return !batches_.empty() || closed_; });
            if (batches_.empty()) {
                return std::nullopt;
            }
            Batch batch = std::move(batches_.front());
            batches_.pop();
            return batch;
        }
    
    private:
        std::mutex mutex_;
        std::condition_variable ready_;
        std::queue<Batch> batches_;
        bool closed_ = false;
    };
    
    int main() {
        constexpr std::size_t threads = 3;
        BatchQueue queue;
        std::vector<Counts> per_thread(threads);
        {
            std::vector<std::jthread> workers;
            for (std::size_t t = 0; t < threads; ++t) {
                workers.emplace_back([&queue, &per_thread, t] {
                    while (std::optional<Batch> batch = queue.pop()) {
                        for (const std::string& read : *batch) {
                            add_kmers(read, per_thread[t]);
                        }
                    }
                });
            }
            Batch batch;
            std::string line;
            while (std::getline(std::cin, line)) {
                batch.push_back(line); // a copy: line is reused for the next read
                if (batch.size() == 2) {
                    queue.push(std::move(batch));
                    batch.clear();
                }
            }
            if (!batch.empty()) {
                queue.push(std::move(batch));
            }
            queue.close();
        } // the workers finish the last batches and join here
        Counts total = merge(per_thread);
        std::println("{} distinct 3-mers, ACA {} times", total.size(),
                     total[0b000100]);
    }

    Output

    9 distinct 3-mers, ACA 6 times

    Three things make this correct:

    • close() after the last batch lets each worker’s pop return std::nullopt once the queue is empty, so the loops end and the std::jthreads can join.
    • Each worker still counts into its own per_thread[t]; the queue is the only shared object, and its mutex guards it.
    • After std::move(batch), the vector is in a valid but unspecified state, so batch.clear() makes it empty again before it’s reused.

    This queue has no size limit. If reading is faster than counting, batches pile up in memory. A bounded queue fixes that: push waits on a second condition variable while the queue holds, say, 16 batches, and pop notifies it after taking one.

    Parallel algorithms for per-read work

    Work that touches each read on its own, without a shared table, fits the parallel algorithms from Parallel work directly. std::transform with std::execution::par writes one result per read into its own slot, and std::transform_reduce adds up a value per read:

    #include <algorithm>
    #include <execution>
    #include <functional>
    #include <numeric>
    #include <print>
    #include <string>
    #include <vector>
    
    std::vector<std::string> reads = {"GATTACA", "GGCCGC", "ATATAT", "CAGG"};
    std::vector<double> gc(reads.size());
    std::transform(std::execution::par, reads.begin(), reads.end(), gc.begin(),
                   [](const std::string& read) {
                       auto n = std::ranges::count_if(
                           read, [](char b) { return b == 'G' || b == 'C'; });
                       return static_cast<double>(n) /
                              static_cast<double>(read.size());
                   });
    std::size_t bases = std::transform_reduce(
        std::execution::par, reads.begin(), reads.end(), std::size_t{0},
        std::plus<>{}, [](const std::string& read) { return read.size(); });
    std::sort(std::execution::par, reads.begin(), reads.end());
    std::println("GC: {::.2f}", gc);
    std::println("{} bases", bases);
    std::println("sorted: {}", reads);

    Output

    GC: [0.29, 1.00, 0.00, 0.75]
    23 bases
    sorted: ["ATATAT", "CAGG", "GATTACA", "GGCCGC"]

    {::.2f} formats each element of the vector with .2f. Four reads are far too few to gain anything, but the same code spreads a million reads over every core.

    Counting k-mers into one table doesn’t fit a parallel algorithm as well: std::reduce would have to merge maps at every step of its tree. For that, your own threads with per-thread counts are simpler and faster.

    Measuring the speedup

    This program makes 200,000 random reads of 150 bases (a fixed seed, so the reads are the same every run), counts their 8-mers with 1, 2, 4, 8 and 16 threads, and times each run, merge included. It’s built with -O2 and without sanitizers, as timings should be:

    #include <chrono>
    #include <cstdint>
    #include <print>
    #include <random>
    #include <string>
    #include <vector>
    
    constexpr int k = 8;
    
    int main() {
        std::mt19937 rng(42); // fixed seed: the same reads every run
        std::uniform_int_distribution<int> pick(0, 3);
        std::vector<std::string> reads(200'000, std::string(150, 'A'));
        for (std::string& read : reads) {
            for (char& base : read) {
                base = "ACGT"[pick(rng)];
            }
        }
        double one_thread_ms = 0;
        for (std::size_t threads : {1, 2, 4, 8, 16}) {
            auto start = std::chrono::steady_clock::now();
            Counts counts = count_parallel(reads, threads);
            std::chrono::duration<double, std::milli> elapsed =
                std::chrono::steady_clock::now() - start;
            double ms = elapsed.count();
            if (threads == 1) {
                one_thread_ms = ms;
            }
            long long total = 0;
            for (auto [code, n] : counts) {
                total += n;
            }
            std::println("{:>2} threads: {:6.1f} ms  speedup {:4.1f}x  {} k-mers",
                         threads, ms, one_thread_ms / ms, total);
        }
    }

    Output from one run (it varies)

     1 threads:  222.7 ms  speedup  1.0x  28600000 k-mers
     2 threads:  116.9 ms  speedup  1.9x  28600000 k-mers
     4 threads:   74.2 ms  speedup  3.0x  28600000 k-mers
     8 threads:   91.4 ms  speedup  2.4x  28600000 k-mers
    16 threads:  133.4 ms  speedup  1.7x  28600000 k-mers

    In this run, on the machine that checks this site’s examples (24 hardware threads), 2 threads were about twice as fast as one and 4 threads about 3 times, but 8 and 16 threads were slower than 4. Your numbers will differ with the machine and from run to run, but a peak like this is common for counting, and the reasons are worth knowing:

    • The merge is serial, and it grows with the threads. Each extra thread adds another map of up to 65,536 entries for one thread to add up at the end. That’s Amdahl’s law from Parallel work: the serial part caps the speedup, and here it even gets bigger.
    • Every thread has its own table, and counting is mostly memory access. Each map holds the same 65,536 k-mers, so 16 threads keep 16 copies. Together they likely no longer fit in the cache the cores share, and a hash lookup per base does little arithmetic, so the threads spend their time waiting for memory (Caches).

    So measure with several thread counts and use the best one, not the largest. Smaller per-thread tables (the flat arrays below) push the peak further out.

    Which one should I use?

    WhatWhenWhyHow
    Threads with per-thread countsAll reads fit in memory, and each thread builds up a table.No locks while counting; one merge at the end.std::vector<Counts> per_thread(threads), merge after join
    Reader thread + work queueThe input is a big file, or reads arrive while you count.Reading and counting overlap, and memory holds only the batches in flight.queue.push(std::move(batch)) / while (auto batch = queue.pop())
    Parallel algorithmsOne result per read, or a sum over reads, with no shared table.One line, and TBB balances the load.std::transform(std::execution::par, …)
    One shared map with a mutexAlmost never.Correct, but the threads queue up for the lock.—

    Rule of thumb: give every thread its own results and combine them once at the end; share only a queue, never the table.

    Under the hood

    Each per-thread map costs memory: with threads threads, up to threads copies of every k-mer’s entry exist before the merge. Each std::unordered_map entry is a separate heap node (a link to the next node, the key and the count) plus a slot in the bucket array. For small k the flat array from 2-bit DNA and k-mers is smaller and faster to update: 4k counters indexed by the code, no hashing, no nodes, and merging is adding arrays element by element. For k = 8 that’s 65,536 counters, 512 KiB of long long per thread.

    For large k (21 or 31, common in genome assembly), the number of distinct k-mers grows with the input, and each thread’s map can hold most of them. A common answer is to split by k-mer instead of by read: every thread scans all reads but keeps only the k-mers whose code falls in its own part of the range, so the parts never need merging. That costs more reading but no duplicate entries.

    Strided splitting and batches both balance the load in their own way. A strided split decides up front and works when reads cost about the same. A queue decides as it goes: a worker that finishes early just takes the next batch.

    Common pitfalls

    A shared progress counter

    A worker that adds 1 to a shared long long reads_done after each read, for a progress message, has the same data race as the shared map: ThreadSanitizer reports it just the same. Make it a std::atomic<long long> (Mutexes and atomics), or count in each thread and add the totals after join, like the k-mer counts.

    Merging with = instead of +=

    total[code] = n; in the merge loop compiles and runs, but each thread’s count replaces the previous thread’s instead of adding to it. With one thread the result is right, which is how this bug survives testing. Compare the result for several thread counts with the one-thread result, as the first example does.

    Holding a view into a line that changes

    std::getline(std::cin, line) reuses line for the next read. If the reader pushed std::string_views into line instead of std::strings, the workers would read text that has already been overwritten, or freed when line grew. Pass owning strings, moved into the batch, across threads; views are only safe while the text they view stays put.

    Try it yourself

    Try it yourself

    Write count_bases(reads, threads), which counts the A, C, G, T and N bases of a std::vector<std::string> of reads (anything else counts as N) and returns them in a std::array<long long, 5>. Split the reads among threads std::jthreads with a strided split, let each thread count into its own array, then add the arrays. For a base’s slot, std::string_view("ACGT").find(base) gives 0 to 3, or std::string_view::npos for anything else. Test it with the reads GATTACA, GGCCNNA, ATATAT and CAGGTN, on 3 threads and on 1.

    Expected output

    [8, 4, 5, 6, 3]
    [8, 4, 5, 6, 3]
    Show a hint

    Make a std::vector of arrays with one array per thread, start one std::jthread per thread in an inner block, and let thread t take reads t, t + threads and so on. After the block, add the arrays element by element.

    Show a solution
    #include <array>
    #include <cstddef>
    #include <print>
    #include <string>
    #include <string_view>
    #include <thread>
    #include <vector>
    
    using BaseCounts = std::array<long long, 5>; // A, C, G, T, N
    
    BaseCounts count_bases(const std::vector<std::string>& reads,
                           std::size_t threads) {
        std::vector<BaseCounts> per_thread(threads, BaseCounts{});
        {
            std::vector<std::jthread> workers;
            for (std::size_t t = 0; t < threads; ++t) {
                workers.emplace_back([&reads, &per_thread, t, threads] {
                    for (std::size_t r = t; r < reads.size(); r += threads) {
                        for (char base : reads[r]) {
                            std::size_t i = std::string_view("ACGT").find(base);
                            ++per_thread[t][i == std::string_view::npos ? 4 : i];
                        }
                    }
                });
            }
        }
        BaseCounts total{};
        for (const BaseCounts& counts : per_thread) {
            for (std::size_t i = 0; i < total.size(); ++i) {
                total[i] += counts[i];
            }
        }
        return total;
    }
    
    int main() {
        std::vector<std::string> reads = {"GATTACA", "GGCCNNA", "ATATAT", "CAGGTN"};
        std::println("{}", count_bases(reads, 3));
        std::println("{}", count_bases(reads, 1));
    }

    Each thread writes only its own array, so there's nothing to lock, and count_bases adds them up after the inner block has joined every thread. Adding integer counts doesn't depend on the order, so 1 and 3 threads give the same totals.

    Saved in this browser only.