22 - 3 - 4
线程、静态、信号量
#include<iostream>#include<thread>#include<vector>using namespace std;// #define sigint_flag truestatic int sigint_flag = true;void thread_say(){ cout << "thread id: " << thread::get_id << endl;};void thread_pause(int i){ while(sigint_flag){ // this_thread::sleep_for(chrono::seconds(i)); this_thread::sleep_for(chrono::seconds(i)); cout << "threads "<< i <<" id: " << this_thread::get_id() << " thread pasue: "<< i << " seconds." << endl; } cout << "threads " << i << " end\n";};void signal_handler(int signum){ cout << "Interrupt signal:" << signum << " received.\n"; //动态的。编译后可以更改 sigint_flag = false; // 静态的(在编译前编译好了,此时更改无效) // #ifdef sigint_flag // #undef sigint_flag // #endif // #define sigint_flag false}int main(){ signal(SIGINT,signal_handler); cout << "main线程的id: " << this_thread::get_id() << "\n"; thread t(thread_say); cout << t.hardware_concurrency() << endl;//可以并发执行多少个(不准确) cout << "native_handle " << t.native_handle() << endl;//可以并发执行多少个(不准确) cout << "线程t的id: " << t.get_id() << endl; //等待线程完成 //该函数会阻塞当前线程。阻塞调用者(caller)所在的线程直至被join的std::thread对象标识的线程执行结束。 t.join(); // thread threads[5]; vector<thread> threads; //线程组 for (int i = 0; i < 5; i++) { //threads[i] = thread(thread_pause, i+1);//线程函数,参数 threads.push_back(thread(thread_pause,i+1)); } cout << "thread jion wait\n" << endl; //线程组等待 for (auto &thread : threads){ cout << "thread: " <<thread.get_id() << " jion\n"; thread.join(); }; cout << "thread end\n";}
define 定义后,sigint后#undef重新#define无效
- define在编译时已经完成,运行时重新define无法更新到code
- thread t[]中
- this_thread::get_id()取得的是主线程id
- vector[thread] t[]中,push_back一个thread可以正常获取Id