This is not the current version of the class.

Synchronization 1: Atomicity

Overview

In this lecture, we discuss multithreading, low-level synchronization, and synchronization objects.

Full notes on synchronization

Multitasking, multiprocessing, multithreading

Example threads

#include <cstdio>
#include <thread>

void print1() {
    printf("Hello from thread 1\n");
}

void print2() {
    printf("Hello from thread 2\n");
}

int main() {
    std::thread t1(print1);
    std::thread t2(print2);
    t1.join();
    t2.join();
}

Thread functions can take arguments

#include <cstdio>
#include <thread>

void printn(int n) {
    printf("Hello from thread %d\n", n);
}

int main() {
    std::thread t1(printn, 1);
    std::thread t2(printn, 2);
    t1.join();
    t2.join();
}

Detached threads

Processes vs. threads

Same program image, different stacks

Advantages of threads for synchronization

A toy task

incr-basic.cc

What?!

incr-basic-noopt

Data races

The Fundamental Law of Synchronization

THOU SHALT NOT HAVE DATA RACES!!!

Atomic operations

addl $0x1,(%rdi)

Atomic instructions

incr-atomic.cc

Mutual exclusion

std::mutex

incr-mutex.cc

std::scoped_lock

Question

incr-spinlock.cc

process4/timedwait-threads.cc