22 - 3 - 4

线程、静态、信号量

  1. #include<iostream>
  2. #include<thread>
  3. #include<vector>
  4. using namespace std;
  5. // #define sigint_flag true
  6. static int sigint_flag = true;
  7. void thread_say()
  8. {
  9. cout << "thread id: " << thread::get_id << endl;
  10. };
  11. void thread_pause(int i)
  12. {
  13. while(sigint_flag){
  14. // this_thread::sleep_for(chrono::seconds(i));
  15. this_thread::sleep_for(chrono::seconds(i));
  16. cout << "threads "<< i <<" id: " << this_thread::get_id()
  17. << " thread pasue: "<< i
  18. << " seconds." << endl;
  19. }
  20. cout << "threads " << i << " end\n";
  21. };
  22. void signal_handler(int signum)
  23. {
  24. cout << "Interrupt signal:" << signum << " received.\n";
  25. //动态的。编译后可以更改
  26. sigint_flag = false;
  27. // 静态的(在编译前编译好了,此时更改无效)
  28. // #ifdef sigint_flag
  29. // #undef sigint_flag
  30. // #endif
  31. // #define sigint_flag false
  32. }
  33. int main()
  34. {
  35. signal(SIGINT,signal_handler);
  36. cout << "main线程的id: " << this_thread::get_id() << "\n";
  37. thread t(thread_say);
  38. cout << t.hardware_concurrency() << endl;//可以并发执行多少个(不准确)
  39. cout << "native_handle " << t.native_handle() << endl;//可以并发执行多少个(不准确)
  40. cout << "线程t的id: " << t.get_id() << endl;
  41. //等待线程完成
  42. //该函数会阻塞当前线程。阻塞调用者(caller)所在的线程直至被join的std::thread对象标识的线程执行结束。
  43. t.join();
  44. // thread threads[5];
  45. vector<thread> threads; //线程组
  46. for (int i = 0; i < 5; i++)
  47. {
  48. //threads[i] = thread(thread_pause, i+1);//线程函数,参数
  49. threads.push_back(thread(thread_pause,i+1));
  50. }
  51. cout << "thread jion wait\n" << endl;
  52. //线程组等待
  53. for (auto &thread : threads){
  54. cout << "thread: " <<thread.get_id() << " jion\n";
  55. thread.join();
  56. };
  57. cout << "thread end\n";
  58. }
  • define 定义后,sigint后#undef重新#define无效

    • define在编译时已经完成,运行时重新define无法更新到code
  • thread t[]中
    • this_thread::get_id()取得的是主线程id
    • vector[thread] t[]中,push_back一个thread可以正常获取Id