Concurrency: goroutines and threads
The task is a sum over two hundred million integers, first on one thread and then split across four. It is the shape of every parallel program: divide the work, start the workers, wait for them, and combine the results without a race. C++ writes it with std::thread and a vector of partial sums; Go with goroutines and a sync.WaitGroup. Both print the same total.
Four threads
Each thread writes its own element of a pre-sized vector, so no two threads touch the same memory and the join is the only synchronisation. The clock covers the loop and the join, not the creation of the vector.
#include <chrono>
#include <iostream>
#include <thread>
#include <vector>
using Clock = std::chrono::steady_clock;
long long term(long long i)
{
return i * (i % 7);
}
long long sum_range(long long from, long long to)
{
long long total = 0;
for (long long i = from; i < to; ++i) {
total += term(i);
}
return total;
}
long long ms_since(Clock::time_point start)
{
return std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - start).count();
}
int main()
{
constexpr long long n = 200000000;
auto start = Clock::now();
const long long sequential = sum_range(0, n);
std::cout << "sequential: " << sequential << " in " << ms_since(start) << " ms\n";
constexpr int workers = 4;
std::vector<long long> partial(workers);
std::vector<std::thread> threads;
start = Clock::now();
for (int w = 0; w < workers; ++w) {
threads.emplace_back([&, w] {
partial[w] = sum_range(n * w / workers, n * (w + 1) / workers);
});
}
for (auto& thread : threads) {
thread.join();
}
long long parallel = 0;
for (long long part : partial) {
parallel += part;
}
std::cout << "parallel: " << parallel << " in " << ms_since(start) << " ms\n";
}
g++ -std=c++23 -O2 -Wall -Wextra sum.cpp -o sum
./sum
sequential: 59999999300000004 in 413 ms
parallel: 59999999300000004 in 206 ms
Four goroutines
The Go version is the same idea with a different vocabulary: go func() starts the worker, wg.Done in a defer marks it finished, and wg.Wait replaces the loop of joins. The index is passed through the closure because Go 1.22 gave every iteration its own variable, and the slice is indexed rather than appended, so the workers never share a length field.
package main
import (
"fmt"
"sync"
"time"
)
func term(i int64) int64 {
return i * (i % 7)
}
func sumRange(from, to int64) int64 {
var total int64
for i := from; i < to; i++ {
total += term(i)
}
return total
}
func main() {
const n int64 = 200_000_000
start := time.Now()
sequential := sumRange(0, n)
fmt.Printf("sequential: %d in %d ms\n", sequential, time.Since(start).Milliseconds())
const workers = 4
partial := make([]int64, workers)
var wg sync.WaitGroup
start = time.Now()
for w := range workers {
wg.Add(1)
go func() {
defer wg.Done()
partial[w] = sumRange(n*int64(w)/workers, n*int64(w+1)/workers)
}()
}
wg.Wait()
var parallel int64
for _, part := range partial {
parallel += part
}
fmt.Printf("parallel: %d in %d ms\n", parallel, time.Since(start).Milliseconds())
}
go run -trimpath ./sum
sequential: 59999999300000004 in 429 ms
parallel: 59999999300000004 in 224 ms
Two runs of the same work: 413 and 429 ms on one thread, 206 and 224 ms on four. The machine has two cores and four hardware threads, so a little over two times is the best either language can do, and the eight percent between the two totals is the run-to-run noise of a shared container. The interesting result is that there is no interesting difference: for arithmetic on a slice, the language does not matter.
The same speed, different machinery
| Question | C++ threads | Go goroutines |
|---|---|---|
| What starts a worker? | std::thread, a new operating system thread | go f(), a goroutine on a pool of threads |
| What does a worker cost? | A stack chosen by the C library and a syscall | A small growable stack, a few hundred bytes of bookkeeping |
| How do workers talk? | A mutex, an atomic or a condition variable | A channel, a mutex or an atomic; all three in the standard library |
| How is a worker stopped? | A flag, a condition variable or a future | A context.Context passed as the first argument |
| What detects a race? | ThreadSanitizer, a compiler flag | The race detector, a go test flag |
The difference that shows up in real code is not speed but the number of workers. A C++ program that starts ten thousand threads is in trouble; a Go program that starts ten thousand goroutines is ordinary, and a server that starts one per request is the normal design. That is the reason channels and select are in the language rather than in a library: they are how a program with thousands of small workers is written.
The race each toolchain reports
Two workers increment one integer without a lock. The C++ program is built with ThreadSanitizer, and this container does not let it start: the sanitizer re-executes itself with a lower ASLR entropy through personality(2), and the call is blocked here. The failure is real and is shown as it came out, not as a substitute for a race report.
#include <iostream>
#include <thread>
int counter = 0;
int main()
{
std::thread a([] { for (int i = 0; i < 100000; ++i) { ++counter; } });
std::thread b([] { for (int i = 0; i < 100000; ++i) { ++counter; } });
a.join();
b.join();
std::cout << counter << "\n";
}
g++ -std=c++23 -O1 -g -fsanitize=thread race.cpp -o race
./race; echo "status: $?"
ThreadSanitizer: CHECK failed: tsan_platform_linux.cpp:290 "((personality(old_personality | 0x0040000))) != ((-1))" (0xffffffffffffffff, 0xffffffffffffffff) (tid=18941)
status: 139
The Go detector is part of the toolchain and needs no re-exec, so the same program gives the report a reader wants:
package main
import (
"fmt"
"sync"
)
func main() {
counter := 0
var wg sync.WaitGroup
for range 2 {
wg.Add(1)
go func() {
defer wg.Done()
for range 100000 {
counter++
}
}()
}
wg.Wait()
fmt.Println(counter)
}
go run -trimpath -race ./race; echo "status: $?"
==================
WARNING: DATA RACE
Read at 0x00c000114028 by goroutine 9:
main.main.func1()
example.com/sum/race/main.go:16 +0x99
Previous write at 0x00c000114028 by goroutine 8:
main.main.func1()
example.com/sum/race/main.go:16 +0xab
Goroutine 9 (running) created at:
main.main()
example.com/sum/race/main.go:13 +0x78
...
185133
Found 2 data race(s)
exit status 66
The counter printed 185133 instead of 200000, and the detector found two races. Where ThreadSanitizer works it produces the same three facts: the two accesses, the threads and the lines that started them. The practical difference is the install: on a machine with a working TSan, a C++ project adds a build configuration and a CI job; in Go, go test -race is one flag, and the toolchain ships the runtime the detector needs.
What to read next
The Go lessons are goroutines, channels and sync.Mutex and shared state; the C++ lesson is threads. The previous page of this group is generics and templates.
The C++ program was built with g++ 15.2.0 (Alpine 15.2.0) at -O2 and the Go programs with go 1.26.10, all run on Alpine Linux 3.24.3 (x86_64) in a Docker container with four CPUs.
Article author: Arthur Isaev