Thread
Using Thread
#include <thread>
#include <iostream>
using namespace std;
void work(int id) {
cout << "thread" << id << endl;
}
int main() {
thread t(work, 1);
t.join();
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);
counter++;
}