?Ubuntu???C++?????,?????C++11????
????????????????????:
1. ?????
??,??????????????:
#include#include
2. ????
?? std::thread
??????????,?????????????:
void print_hello() { std::cout << "Hello from thread!" << std::endl; } int main() { std::thread t(print_hello); // ??????? print_hello ?? t.join(); // ?????? return 0; }
3. ???????
?Ubuntu???C++??????,??????C++11?????????,???pthread????,??g++???:
g++ -std=c++11 -pthread -o my_program my_program.cpp
4. ?? join()
? detach()
join()
:???????detach()
:???????,??????????
std::thread t1(print_hello); // ??????? print_hello ?? t1.join(); // ???? t1 ?? // ?? detach std::thread t2(print_hello); // ??????? print_hello ?? t2.detach(); // ?? t2 ?????
5. ????
??????????????????????????????(std::mutex
)?????(std::condition_variable
)?????????
??:???????????
#include
#include
#include
std::mutex mtx; // ???
void print_message(const std::string& message) {
std::lock_guard lock(mtx); // ???????????
std::cout << message << std::endl;
}
int main() {
std::thread t1(print_message, "Thread 1");
std::thread t2(print_message, "Thread 2");
t1.join();
t2.join();
return 0;
}
6. ???????
????????????,?????????,?bees???????????????????,?????????????
7. ????
- ??????:??????????,???????????????
- ??????:?????(?GDB)???????????,????????????
- ??????:????????????????,?Valgrind?Helgrind?,?????????????????
???????????,????Ubuntu??????C++??????????????????!