Notes on C++ Concurrent Programming

Common Headers


In [ ]:
#include <iostream>
#include <thread>

using namespace std;

Introduction to multithread

  1. Pros

    • fast to start

    • low overhead

  2. Cons

    • difficult to implement

    • can't run on distributed system.

An Example


In [ ]:
void function_1() {
    cout << "This is a test" << endl;
}

int main() {
    thread t1(function_1); //t1 starts running
    //t1.join(); //main thread waits for t1 to finish
    t1.detach(); //t1 will freely on its own --- daemon process
    
    if (t1.joinable())
        t1.join();
    
    return 0
}

Thread Management

An Example


In [ ]:
class Fctor {
public:
    void operator() () {
        for (int i = 0; i > -100; i--) {
            cout << "from t1 " << i << endl;
        }
    }
}

In [ ]:
int main() {
    //thread t1(function_1);//t1 starts running
    
    Factor fct;
    thread t1(fct); // t1((Factor()))
    
    
    try {
        for (int i = 0; i < 100; i++) {
            cout << "from main: " << i << endl;
        }
    } catch (...) {
        t1.join();
        throw;
    }
}
  • passing a parameter to the thread

In [ ]:
class Fctor {
public:
    void operator()(string& msg) {
        cout << "t1 says: " << msg << endl;
        msg = "Trust is the mother of deceit.";
    }
}

int main() {
    string s = "Where there is no trust, there is no love";
    cout << std::this_thread::get_id() << endl;
    //thread t1((Fctor()), std::ref(s));//t1 starts running
    thread t1((Fctor()), std::move(s));//t1 starts running
    
    thread t2 = t1; //compile error. 
    
    thread t3 = std::move(t1);
    
    t1.join();
    
    return 0;
}