boost创建scoped_thread

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一 概述

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/boost_1_74_0 -L /opt/boost/boost_1_74_0/stage/lib -lboost_thread -pthread

2.profile:

export LD_LIBRARY_PATH=/usr/local/lib:/opt/boost/boost_1_74_0/stage/lib:$LD_LIBRARY_PATH
source profile

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值