(1)函数指针
情况一:主线程有join,正常执行
#include <thread>
#include <iostream>void work(int num) {while(num-- > 0) {std::cout << num << std::endl;}
}int main() {std::thread t(work, 5);t.join();return 0;
}
情况二:主线程没有join,出现core dump
#include <thread>
#include <iostream>void work(int num) {while(num-- > 0) {std::cout << num << std::endl;}
}int main() {std::thread t(work, 5);//t.join();return 0;
}
(2)lambda表达式
#include <thread>
#include <iostream>int main(int argc, char* argv[]){std::thread t([](int num){while (num-- > 0) {std::cout << num << std::endl;}}, 5);t.join();return 0;
}
(3)仿函数
#include <thread>
#include <iostream>
#include <unistd.h>class Demo {
public:void operator()(int num) {while(num-- > 0) {std::cout << num << std::endl;}}
};int main(int argc, char* argv[]) {std::thread t(Demo(), 5);t.join();return 0;
}
(4)静态成员函数
#include <thread>
#include <iostream>class Demo {
public:static void work(int num){while(num-- > 0) {std::cout << num << std::endl;}}
};int main(int argc, char* argv[]) {std::thread t(&Demo::work, 5);t.join();return 0;
}
(5)非静态成员函数
#include <thread>
#include <iostream>class Demo {
public:void work(int num){while(num-- > 0) {std::cout << num << std::endl;}}
};int main(int argc, char* argv[]) {Demo d;std::thread t(&Demo::work, &d, 5);t.join();return 0;
}