Created
March 3, 2014 15:30
-
-
Save sukinull/9327390 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// main.cpp | |
// OxAsio | |
// | |
// Created by sukinull on 1/8/14. | |
// Copyright (c) 2014 sukinull. All rights reserved. | |
// | |
// based on code, here - http://thisthread.blogspot.tw/2011/04/multithreading-with-asio.html | |
// you need C++11, and C++11 enabled boost | |
#include <iostream> | |
#include <functional> | |
#include <boost/asio.hpp> | |
#include <boost/thread.hpp> | |
namespace { | |
void jobOne(int secs) // 3. | |
{ | |
std::cout << "Start jobOne: " << secs << std::endl; | |
boost::this_thread::sleep(boost::posix_time::millisec(1000 * secs)); | |
std::cout << "End jobOne: " << secs << std::endl; | |
} | |
} | |
/** | |
* Mark and Remark 5.1 and 5.2 to see what's the different between post() and dispatch() | |
*/ | |
int main(int argc, char* argv[]) { | |
boost::asio::io_service svc; // 2. | |
boost::thread_group threads; | |
{ | |
// about `boost::asio::io_service::work', read http://stackoverflow.com/questions/17156541/why-do-we-need-to-use-boostasioio-servicework | |
std::auto_ptr<boost::asio::io_service::work> work(new boost::asio::io_service::work(svc)); //3. | |
threads.create_thread(boost::bind(&boost::asio::io_service::run, &svc)); // 4. | |
threads.create_thread(boost::bind(&boost::asio::io_service::run, &svc)); | |
svc.post(std::bind(jobOne, 5)); // 5. | |
svc.dispatch(std::bind(jobOne, 7)); // 5.1 run jobOne(7) immediately | |
// svc.post(std::bind(jobOne, 7)); // 5.2 enque jobOne(7) to waiting queue | |
svc.post(std::bind(jobOne, 3)); | |
// svc.stop (); // 6. | |
} | |
threads.join_all(); // 7. | |
return EXIT_SUCCESS; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment