Thread

Using Thread

  • 1.Create thread
#include <thread>
#include <iostream>

using namespace std;

void work(int id) {
  cout << "thread" << id << endl;
}

int main() {
  thread t(work, 1);
  t.join(); // wait for the thread finish execute.

  thread t1([]{
    cout << "Hello thread" << endl;
  })

  return 0;
}

  • 2.Difference between join and detach
method remark
join() stuck current thread until sub thread execute finished
detach() let sub thread become “background thread”, but it might be killed forcely when the process is exit

Lock

  • 1.mutex, full name mutual exclusion: Only one thread can access some code or some share data at the same time

  • 2.Why we should use lock (If we don’t use lock):

    • Data race

    • Crach

    • Dead loop

    • Lost/repeat tasks

    • Unknow error

  • 3.The principle of mutex

    • Mutex will lock the share data before each thread access these data.

    • Unlock these share data after access it.

    • If a thread is locked, other threads will start waiting.

  • 4.Usage

#include <mutex>

std::mutex m;

{
  std::lock_guard<std::mutex> lock(m); // Auto Lock
  counter++;                           // Critical section
}                                      // Auto unlock
  • 5.unique_lock

  • 6.mutex use cases

    • Modify share variables
      counter++;
    
    • push/pop container in multiple threads;
      queue.push(...);
      queue.pop();
      vector.push_back();
    
    • Write file in multiple threads. (To protect write file, otherwise the file data may has error)