#include <iostream>
#include <asio.hpp>
#include <thread>
#include <memory>
#include <vector>
#include <mutex>
#include <chrono>
std::mutex global_stream_lock;
void WorkerThread(std::shared_ptr<asio::io_service> iosvc, int counter)
{
global_stream_lock.lock();
std::cout << "Thread " << counter << "Start.\n";
global_stream_lock.unlock();
while(true){
try{
asio::error_code ec;
iosvc->run(ec);
if(ec)
{
global_stream_lock.lock();
std::cout << "message : " << ec << ".\n";
global_stream_lock.unlock();
}
break;
}
catch (std::exception& e)
{
global_stream_lock.lock();
std::cout << "message " << e.what() << "\n";
global_stream_lock.unlock();
}
}
global_stream_lock.lock();
std::cout << "Thread" << counter << " End.\n";
global_stream_lock.unlock();
}
void TimerHandler(const asio::error_code& ec)
{
if(ec)
{
global_stream_lock.lock();
std::cout << "Error Message: " << ec << "\. \n";
global_stream_lock.unlock();
}
else
{
global_stream_lock.lock();
std::cout << "you have waited for 10 seconds. \n";
std::cout << "now press ENTER to exit. \n";
global_stream_lock.unlock();
}
}
int main(int argc, char ** argv)
{
std::shared_ptr<asio::io_service> io_svc(new asio::io_service);
std::shared_ptr<asio::io_service::work> worker(new asio::io_service::work(*io_svc));
asio::io_service::strand strand(*io_svc);
global_stream_lock.lock();
std::cout << "Thr Program will wait 10 seconds.\n";
global_stream_lock.unlock();
std::vector<std::thread> threadGroup;
for(int i = 1; i <= 5; ++i)
threadGroup.emplace_back(std::bind(&WorkerThread, io_svc, i));
asio::system_timer timer(*io_svc);
timer.expires_from_now(std::chrono::seconds(10));
timer.async_wait(TimerHandler);
std::cin.get();
io_svc->stop();
std::for_each(threadGroup.begin(), threadGroup.end(), [](std::thread& thread){ thread.join(); });
system("pause");
return 0;
}
'C.C++ > 코드' 카테고리의 다른 글
case에 해싱을 통해 string으로 처리하는 것 실제 사용 예 (0) | 2018.05.06 |
---|---|
thread_group (1) | 2018.04.24 |
asio io_service 한방이해 (0) | 2018.04.15 |
예외처리가 안되었을 경우에 terminate 에서 abort 말고 커스텀 함수 호출하는 법 (0) | 2017.12.10 |
에러값 리턴 (0) | 2017.05.23 |
댓글