Threads

Whats a thread?

Threads can allow a program to execute multiple sections of code at once

Uses for threads

  • Faster code (execute on multiple cores at the same time)
  • Non blocking IO (one thread waits for input while another does work)

Side note: processes

  • A process can have multiple threads
  • Heavier weight than threads
  • A process is more like an entire program
  • Learn more in OS

Using threads

How to use threads

  • pthread in C (compile with -lpthread)
  • std::thread in C++ (compile with -lpthread)
  • Thread in Java
  • *Python threading gets a bit weird

C++ example

#include <iostream>
#include <string>
#include <thread>

void thread_test(std::string id, unsigned long n) {
    for (int i = 0; i < n; i++) {
        std::cout << id << " " << i << '\n';
    }
}

void demo1() {
    std::thread t1{thread_test, "thread1", 10};

    //Main thread continues executing here
    // ...
    // ...
    // ...

    //Main thread waits here until
    t1.join();
}

Demo

Making a simple program with threads!

Make a program to find the sum of an array

Tips: Split the array in half and have one thread work on each half

//Useful code bits
#include <thread>

//compile with this
g++ mycode.cpp -lpthread

//std::thread t(myfunction, arg1, arg2);
//t.join();

Live coding demo

Shared memory

  • Threads can access global variables
  • Efficient way for threads to communicate
  • Can be dangerous (race conditions)

Fixing race conditions

Mutex locks

  • When locked other threads will not run during that code segment
  • Used to give only one thread access to data

Example

Threads

By theasocialmatzah

Threads

  • 355