一 概述
scoped_thread创建的线程在作用域范围外自动join,不需要手动写join函数,如下代码展示了使用scoped_thread创建线程,并使用bind关联线程函数和相关参数,向文件写入一些字符。
二 代码
#include <fstream>
#include <iterator>
#include <algorithm>
#include <boost/thread.hpp>
#include <boost/thread/scoped_thread.hpp>
void fill_file(char fill_char, std::size_t size, const char *file_path) {
std::ofstream ofs(file_path);
if (!ofs) {
return;
}
if (!ofs.is_open()) {
ofs.close();
return;
}
std::fill_n(std::ostreambuf_iterator<char>(ofs), size, fill_char);
ofs.close();
}
void example() {
boost::scoped_thread<boost::join_if_joinable>t(boost::bind(&fill_file, 'A', 1024, "./11.txt"));
}
int main() {
example();
return 0;
}
1.编译:
g++ -std=c++11 -g -o Test test.cpp -I ./ -I /opt/boost/bo

本文介绍了如何使用Boost库的scoped_thread创建线程,线程在作用域结束时自动join,同时展示了如何通过bind函数关联线程函数和参数,实现在指定文件中填充字符的操作。
最低0.47元/天 解锁文章
420

被折叠的 条评论
为什么被折叠?



