// PrintString.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <boost\thread\thread.hpp>
#include <boost\thread\mutex.hpp>
#include <boost\thread\condition_variable.hpp>
#include <vector>
#include <iostream>
using namespace boost;
class CPrintString
{
public:
CPrintString();
~CPrintString();
void PrintString(std::vector<std::string> &vc_string);
private:
void PrintSingleString(int n_index);
private:
std::string str_print_;
std::vector<std::string> vc_string_;
mutex m_mutex_;
condition_variable va_notyfi_;
int n_cnt_;
};
CPrintString::CPrintString()
{
n_cnt_ = 10;
}
CPrintString::~CPrintString()
{
}
void CPrintString::PrintString(std::vector<std::string> &vc_string)
{
if (vc_string.empty())
{
return;
}
str_print_ = vc_string.at(0);
vc_string_ = vc_string;
thread_group tg;
for (size_t i = 0; i < vc_string.size(); i++)
{
tg.create_thread(bind(&CPrintString::PrintSingleString, this, i));
}
tg.join_all();
}
void CPrintString::PrintSingleString(int n_index)
{
unique_lock<mutex> lock(m_mutex_);
int n_cnt = 0;
while (n_cnt < n_cnt_)
{
va_notyfi_.wait(lock, [&]()->bool { return (str_print_ == vc_string_.at(n_index) ? true : false); });
std::cout << str_print_ << std::endl;
if (n_index == vc_string_.size() - 1)
{
str_print_ = vc_string_.at(0);
}
else
{
str_print_ = vc_string_.at(n_index + 1);
}
n_cnt++;
va_notyfi_.notify_all();
}
}
int main()
{
CPrintString printString;
std::vector<std::string> vc_string;
vc_string.push_back("A");
vc_string.push_back("B");
vc_string.push_back("C");
printString.PrintString(vc_string);
std::system("pause");
return 0;
}
boost线程循环打印字符ABC
最新推荐文章于 2023-08-18 09:38:59 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)