CS106L笔记:Multi-threading
sixwalter Lv6

Multi-threading

Thread

  • threads are ways to parallelise execution

what’s the problem?

image-20230329092820246
  • DATA RACE!

  • use LOCK!

image-20230329092948175 image-20230329093018757 image-20230329093102789 image-20230329093809261
1
2
3
4
5
6
7
8
9
10
11
12
13
14
//std::mutex mtx;
void greet(int id){
//std::lock_guard<std::mutex> lg(mtx);
cout<<"my name is "<<id<<endl;
}
int main(){
cout<<"Greetings from my threads..."<<endl;
std::thread thread1(greet,id1);
std::thread thread2(greet,id2);
thread1.join();
thread2.join();
cout<<"All greetings done!"<<endl;
return 0;
}
image-20230329094700034
  • Data Racing is unpredictable!

use lock_guard to ensure the greeting is atomic:

1
2
3
4
5
std::mutex mtx;
void greet(int id){
std::lock_guard<std::mutex> lg(mtx);
cout<<"my name is "<<id<<endl;
}

use join to let the main wait the thread to finish

1
2
thread1.join();
thread2.join();
image-20230329095900412
  • the results seems fine!
1
2
3
4
5
6
7
8
9
10
11
//...work with vector if threads
vector<std::thread> threads;

for(size_t i=0; i < kNumThreads; ++i){
threads.push_back(std::thread(greet,i));
}

for(std::thread& t: threads){
t.join();
}
//...
  • Post title:CS106L笔记:Multi-threading
  • Post author:sixwalter
  • Create time:2023-08-05 11:14:26
  • Post link:https://coelien.github.io/2023/08/05/course-learning/CS-106L/Multi-Threading/
  • Copyright Notice:All articles in this blog are licensed under BY-NC-SA unless stating additionally.
 Comments