Chapter 1 · Section 6 of 8 · 4 min read
Other languages
The counter from this chapter in four more languages. For each one the section says what the language's own documentation promises. I could run the C++ and Python versions on this machine. I could not run the Java and Rust ones (no Java runtime and no Rust compiler here), so those two are marked and are not part of this repository's checks.
C++
// The Chapter 1 counter with a std::mutex. Compile and run:
// clang++ -std=c++20 -pthread mutex.cpp -o mutex && ./mutex
// With the thread sanitizer: add -fsanitize=thread (it reports nothing here).
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>
int main() {
const int workers = 8, per = 100000;
int count = 0;
std::mutex mu; // guards count
std::vector<std::thread> threads;
for (int i = 0; i < workers; i++) {
threads.emplace_back([&] {
for (int j = 0; j < per; j++) {
std::lock_guard<std::mutex> guard(mu); // unlocks when guard goes out of scope
count++;
}
});
}
for (auto& t : threads) t.join();
std::cout << "expected " << workers * per << ", got " << count << "\n";
}Built with Apple clang 21 and run twice, it printed expected 800000, got 800000 both times. Built with -fsanitize=thread it ran with no sanitizer report. Without the mutex, Chapter 0's version lost most of its updates.
What the documentation says (std::mutex, cppreference.com):
- "mutex offers exclusive, non-recursive ownership semantics." A thread owns the mutex from a successful
lockortry_lockuntil it callsunlock, and meanwhile other threads block (or getfalsefromtry_lock). - "The behavior of a program is undefined if a mutex is destroyed while still owned by any threads, or a thread terminates while owning a mutex."
- "std::mutex is neither copyable nor movable." That is the compiler-enforced version of Go's rule that you must not copy a mutex.
C++ has std::lock_guard, which the documentation calls "a convenient RAII-style mechanism for owning a mutex for the duration of a scoped block": the mutex is locked when the guard is created and released when it goes out of scope. That is C++'s version of Go's defer mu.Unlock(). The same page warns of a classic mistake: writing std::lock_guard<std::mutex>(mtx); without a name "thereby not actually constructing a lock that holds a mutex for the rest of the scope."
Python
# The Chapter 1 counter with threading.Lock. Run: python3 mutex.py
import threading
workers, per = 8, 100_000
count = 0
lock = threading.Lock() # guards count
def work():
global count
for _ in range(per):
with lock: # acquire on entry, release on exit
count += 1
threads = [threading.Thread(target=work) for _ in range(workers)]
for t in threads:
t.start()
for t in threads:
t.join()
print(f"expected {workers * per}, got {count}")Run on Python 3.14.0 it printed expected 800000, got 800000.
What the documentation says (threading, docs.python.org):
- "A primitive lock is a synchronization primitive that is not owned by a particular thread when locked." That matches Go's rule and is the opposite of the Linux kernel's.
- A
withstatement callsacquirewhen the block is entered andreleasewhen it is exited. The docs show it is equivalent toacquire()followed bytry: ... finally: release(). - Reentrancy is a separate class: the module has
RLockobjects alongsideLockobjects.
Rust
Illustrative, not compiled in this repository.
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let count = Arc::new(Mutex::new(0)); // the data lives inside the mutex
let handles: Vec<_> = (0..8)
.map(|_| {
let count = Arc::clone(&count);
thread::spawn(move || {
for _ in 0..100_000 {
*count.lock().unwrap() += 1; // the guard unlocks at the end of the statement
}
})
})
.collect();
for h in handles {
h.join().unwrap();
}
println!("{}", *count.lock().unwrap());
}What the documentation says (Mutex in std::sync, Rust standard library, std 1.100.0):
- Each mutex has a type parameter for "the data that it is protecting". The data "can only be accessed through the RAII guards returned from lock and try_lock, which guarantees that the data is only ever accessed when the mutex is locked."
- Poisoning. "a mutex becomes poisoned if it recognizes that the thread holding it has panicked. Once a mutex is poisoned, all other threads are unable to access the data by default as it is likely tainted (some invariant is not being upheld)." That is why
lock()returns aResult, which the sample unwraps.
The design difference to notice is that in Go the mutex sits next to the data and a comment says what it guards. In Rust the data sits inside the mutex, so you cannot reach it without locking.
Java
Illustrative, not compiled in this repository.
import java.util.concurrent.locks.ReentrantLock;
class Counter {
private final ReentrantLock lock = new ReentrantLock();
private int n; // guarded by lock
void inc() {
lock.lock();
try {
n++;
} finally {
lock.unlock();
}
}
}The JDK documentation (ReentrantLock, Java SE 21 & JDK 21) says: "It is recommended practice to always immediately follow a call to lock with a try block, most typically in a before/after construction", which is the same job as Go's defer. It also describes the lock as "owned by the thread last successfully locking, but not yet unlocking it", and says that lock "will return immediately if the current thread already owns the lock". That second sentence is reentrancy, which Go's mutex does not have. Chapter 3 is about it.
Comparing the four
C++ std::mutex | Python threading.Lock | Rust Mutex<T> | Java ReentrantLock | |
|---|---|---|---|---|
| Where the data lives | Next to the mutex | Next to the lock | Inside the mutex | Next to the lock |
| How it is released | lock_guard goes out of scope | with block ends | The guard is dropped | finally { unlock(); } |
| Recursive locking | "non-recursive" | RLock is a separate class | Not stated on the page I read | Allowed |
| Special rule | Undefined behaviour if destroyed while owned | Not owned by a particular thread | Poisoning after a panic | Optional fairness |
| Can it be copied? | "neither copyable nor movable" | Not stated on the page I read | Not stated on the page I read | Not stated on the page I read |
"Not stated on the page I read" means exactly that. It is not a claim that the answer is no.