1. #include <thread>
    2. #include <iostream>
    3. #include <mutex>
    4. using namespace std;
    5. mutex g_mutex;
    6. void T1(){
    7. g_mutex.lock();
    8. cout << "Hello" << endl;
    9. g_mutex.unlock();
    10. }
    11. void T2(const char* str){
    12. g_mutex.lock();
    13. cout << str << endl;
    14. g_mutex.unlock();
    15. }
    16. int main(){
    17. thread t1(T1);
    18. thread t2(T2, "Hello world");
    19. t1.join();
    20. t2.join();
    21. return 0;
    22. }

    存取钱案例

    1. #include <thread>
    2. #include <iostream>
    3. #include <mutex>
    4. using namespace std;
    5. //取钱
    6. void Withdraw(mutex& m, int& money){
    7. for(int index = 0; index<100; index++){
    8. m.lock();
    9. money += 1;
    10. m.unlock();
    11. }
    12. }
    13. //存钱
    14. void Deposit(mutex& m, int& money){
    15. for(int index = 0; index<100; index++){
    16. m.lock();
    17. money -= 2;
    18. m.unlock();
    19. }
    20. }
    21. int main(){
    22. int money = 2000;
    23. mutex m;
    24. cout << "current money is:" << money << endl;
    25. //thread中传引用用ref
    26. thread t1(Deposit, ref(m), ref(money));
    27. thread t2(Withdraw, ref(m), ref(money));
    28. t1.join();
    29. t2.join();
    30. cout << "Finally money is:" << money << endl;
    31. return 0;
    32. }

    线程的交互与移动