Skip to content

Latest commit

 

History

History
143 lines (115 loc) · 5.76 KB

W3_thread.md

File metadata and controls

143 lines (115 loc) · 5.76 KB

CS 3 interprocess communication

Race condition

when multiple processes access a shared resource, results are indeterminate

  • critical region: part of the program where shared resources are accessed
  • mutual exclusion: guarantee that only one process/thread executes within the critical region at any given point

condition for mutual exclusion

a good solution:

  1. no processes simultaneously inside critical regions
  2. no assumptions about speeds or number of CPUS
  3. no process running outside critical region block others
  4. no process has to wait forever to enter

achieving

  • acquire lock to enter a critical region
  • release lock when exit

Mutual Exclusion

  • Busy Waiting
    • Strict alternation
    • TSL with busy waiting
  • Blocking
    • Mutex

_Chat-GPT: Busy waiting and Blocking

Busy waiting refers to a situation in which a process or thread continuously checks for a condition to become true, without releasing the CPU or performing any other useful work during that time. It “waits” by repeatedly checking a condition, typically in a tight loop, until the condition is met. This can result in high CPU usage and inefficiency, as the process doesn’t give up control of the CPU and performs unnecessary computations.

problems:

  • CPU wastage: Since the process is continuously checking the condition, it uses CPU cycles without doing meaningful work.
  • System inefficiency: If many processes or threads are using busy waiting, they can degrade the overall performance of the system.

Blocking: Using synchronization primitives such as mutexes, semaphores, or condition variables, a thread can block itself and release the CPU until the condition is met.

a example of mutex

#include <iostream>
#include <thread>
#include <mutex>

std::mutex mtx;   // Declare a mutex
int counter = 0;   // Shared resource (counter)

// Function to increment the counter
void incrementCounter() {
    // Lock the mutex before accessing the shared resource
    mtx.lock();
    // Critical section (only one thread can access this at a time)
    counter++;
    std::cout << "Counter: " << counter << std::endl;
    // Unlock the mutex after accessing the shared resource
    mtx.unlock();
}

int main() {
    // Create multiple threads that increment the counter
    std::thread t1(incrementCounter);
    std::thread t2(incrementCounter);
    std::thread t3(incrementCounter);
    
    // Wait for all threads to finish
    t1.join();
    t2.join();
    t3.join();
    
    return 0;
}

_Chat-GPT: TSL

TSL stands for Test and Set Lock. It’s a hardware-level atomic instruction used to implement mutual exclusion (mutex), especially in busy waiting scenarios.

The key idea: it checks a memory location and sets it to a new value in one atomic operation — no other thread or CPU can interrupt in between.

// Shared lock variable
int lock = 0;

void acquire_lock() {
    while (TSL(&lock) == 1) {
        // Busy wait — keep spinning until lock becomes 0
    }
}

void release_lock() {
    lock = 0;
}

TSL (Spinlock): Uses busy waiting (spinning), making it fast for short-term locks but inefficient

when held for long durations. It doesn’t involve blocking and wastes CPU resources while waiting.

The TSL operation typically performs the following steps:

  1. Load the current value of the LOCK variable into a register.

  2. Set the value of LOCK to 1 (indicating the lock is now taken).

  3. Return the previous value of LOCK (whether it was 0 or 1). The atomic nature of TSL ensures that these steps are executed as a single, uninterruptible operation. No other thread or processor can interfere during the execution of the TSL instruction itself. This atomicity is what makes TSL useful for implementing spinlocks and synchronization primitives.

_Chat-GPT: Mutex

Mutex is a higher-level synchronization primitive that can be implemented using atomic operations like TSL or other mechanisms, but mutexes typically involve blocking a thread when the lock is unavailable. This is done by the operating system or threading library, which puts the thread to sleep rather than having it busy wait (spin).

In a mutex implementation, a context switch can happen when the thread is blocked (waiting for the mutex to be available), and the operating system schedules another thread to run. After the lock becomes available, the blocked thread will be scheduled again.

strict alternation

provide a int flag = 0,

  • when flag == 0, thread A takes the turn, then changes to 1
  • when flag == 1, thread B takes the turn, then changes to 0
  • Dangerous:
    • A finished critical, TURN = 1,
    • B finished too, TURN = 0,
    • A start a loop again, and finished, TURN = 1
    • B still stuck at non-critical, TURN = 1
    • A start a loop, but TURN = 1, it must wait B finish the non-critical, and start a new loop, finish critical, then change TURN = 0

Mutex

  • copy Mutex to register an set mutex to 1
  • was mutex zero
  • if zero, it was unlocked, so return
  • else it busy, schedule another thread
  • try again

mutex yield will not release the lock, but only let other thread not using this lock to run

  • advantages
    • improve CPU efficiency
    • Reduces contention: Prevents excessive lock competition in high-thread environments.
  • disadvantages
    • If the lock is expected to be released very soon, spinning (busy-waiting) can be more efficient.
    • If too many threads yield frequently, it can cause excessive context switching overhead.

Test and set lock

  • hardware support for locking
  • Atomic operations
    1. copy contents of LOCK into REGISTER
    2. Store non-zero value in LOCK
  • atomic are indivisible, all or nothing

Blocking

  • general approach
    • check if entry is allowed
    • if not, let another thread use the cpu