tags : Operating Systems, Concurrency

Each thread executes a thread function

Types

preemptivenot preemptive/cooperative
parallelnative threadsprograms on different computers?
non-parallelgreen threadsCoroutines

Preemptive/Non Preemptive

  • Having the ability the preempt means less chances of starvation.

Native Threads

OS threads basically

pthreads (posix threads)

  • A pthread can be either be created as
    • A joinable thread (the default)
    • A detached thread (cleaned up automatically when it terminates)
  • Thread cancellation are of three types(pthread_setcanceltype)
    • sync
    • async
    • uncancellable (critical section)

Green Threads

  • Language agnostic idea, implementations differ.
  • User-level threads that are scheduled by a runtime/scheduler/library instead of the OS. They usually sit on top of OS threads.
  • Green threads have threading semantics, that means that you need to deal with mutexes, atomics, etc.
  • You should code as though the context can switch at any time
  • Python’s greenlets. Golang has mix of greenthreads and os threads w goroutines etc. Ruby’s fibers are green threads. (See Python Concurrency)

Coroutines

Thread Safety

  • Thread-Safety is just the ability to maintain an object’s invariants in a multi-threaded environment.
  • Libraries/Methods can be: Thread safe, Conditionally safe, Not thread safe

When to use synchronization?

  • Always avoid synchronization/shared-state if possible.
  • If possible to keep things thread-local, do it, even if it costs some memory.

No Shared State

  • Re-entrancy
    • Subroutine is called reentrant if multiple invocations can safely run concurrently, i.e execution and then safely be called again/re-enter before its previous invocations complete execution.
    • See Interrupts, Soft IRQs are re-enterant functions.
  • Tread local storage
    • It’s just storage specific to the running thread
    • Many threads can have a variable called a; a is local to each thread. One usage can be multiple threads accumulating information into a global variable with some kind of sync ofc.
  • Immutable objects: What functional languages do
  • Concurrency in Golang provides us with channels which allow goroutines to communicate w each other via message passing rather than shared state.

There is shared state

  • Mutual Exclusion (Blocking)
  • Atomic Operations (Non blocking)