以boost为例。boost::thread有两个构造函数:
(1)thread():构造一个表示当前执行线程的线程对象;
(2)explicit thread(const boost::function0
boost::function0
方法1:通过无参数的函数创建线程
#include <iostream>
#include <boost/thread.hpp>
void Hello() {
// 睡眠一秒以模拟数据处理。
boost::this_thread::sleep(boost::posix_time::seconds(1));
std::cout << "Hello, World!" << std::endl;
}
int main() {
// 创建一个线程对象,注意函数 Hello 将立即运行。
boost::thread hello_thread(Hello);
// 等待线程结束。
// 否则线程还没执行(完),主程序就已经结束了。
hello_thread.join();
return 0;
}
方法2:通过带参数的函数创建线程
#include <iostream>
#include <boost/thread.hpp>
void Hello(const char* what) {
// 睡眠一秒以模拟数据处理。
boost::this_thread::sleep(boost::posix_time::seconds(1));
std::cout << "Hello, " << what << "!" << std::endl;
}
int main() {
boost::thread hello_thread(Hello, "World");
// 等价于使用 bind:
// boost::thread hello_thread(boost::bind(&Hello, "World"));
hello_thread.join();
return 0;
}
方法3:通过一个函数对象,即仿函数(functor)创建线程
#include <iostream>
#include <boost/thread.hpp>
class Hello {
public:
void operator()(const char* what) {
boost::this_thread::sleep(boost::posix_time::seconds(1));
std::cout << "Hello, " << what << "!" << std::endl;
}
};
int main() {
Hello hello;
// 方式一:拷贝函数对象。
boost::thread hello_thread(hello, "World");
hello_thread.join();
// 方式二:不拷贝函数对象,通过 boost::ref 传入引用。
// 用户必须保证被线程引用的函数对象,拥有超出线程的生命期。
// 比如这里通过 join 线程保证了这一点。
boost::thread hello_thread_ref(boost::ref(hello), "World");
hello_thread_ref.join();
return 0;
}
方法4:通过一个成员函数创建线程
与前例不同之处在于,需要以 bind
绑定 this
指针作为第一个参数。
#include <iostream>
#include <boost/thread.hpp>
class Hello {
public:
Hello() {
boost::thread hello_thread(boost::bind(&Hello::Entry, this, "World"));
hello_thread.join();
}
private:
// 线程函数
void Entry(const char* what) {
boost::this_thread::sleep(boost::posix_time::seconds(1));
std::cout << "Hello, " << what << "!" << std::endl;
}
};
int main() {
Hello hello;
return 0;
}
tip: 关于thread::join() 和thread::detach(), 参见https://www.cnblogs.com/zhanghu52030/p/9166526.html
原文链接: https://www.cnblogs.com/zhanghu52030/p/9166434.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/275767
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!