To learn C ++ 11 (and upgrade), I write a simple http server using boost asio and C ++ 11 (for streaming and lambdas).
I want to test the new C ++ 11 lambdas and std :: thread, so I tried to run io_service.run() like this in std :: thread with lambda:
#include <iostream> #include <thread> #include <boost/asio.hpp> #include <boost/thread.hpp> using std::cout; using std::endl; using boost::asio::ip::tcp; class HttpServer { public: HttpServer(std::size_t thread_pool_size) : io_service_(), endpoint_(boost::asio::ip::tcp::v4(), 8000), acceptor_(io_service_, endpoint_) { } void Start() { acceptor_.listen(); cout << "Adr before " << &io_service_ << endl; std::thread io_thread([this](){ cout << "Adr inside " << &io_service_ << endl; io_service_.run(); }); io_thread.join(); } private: boost::asio::io_service io_service_; tcp::endpoint endpoint_; tcp::acceptor acceptor_; }; int main() { HttpServer server(2); server.Start(); }
This results in a segmentation error. Also, sometimes it runs cout inside the lambda, sometimes not (although endl should be hiding). In any case, it prints the correct io_service_ address. However, when I replace std::thread with boost::thread (no other change!), Everything works fine.
I would appreciate if anyone has an idea where the problem is caused (maybe asio, std :: thread or std :: lambda).
Additional Information:
According to another post, accessing the io_service_ member inside lambda is good at capturing this , as I do.
I am running gcc 4.6.1 on Ubuntu and upgrading 1.46. G ++ options:
g++ -std=c++0x -static -I/home/andre/DEV/boost_1_48_0/include/ -L/home/andre/DEV/boost_1_48_0/lib/ -o webserver main.cpp -lboost_system -lboost_thread -lpthread
Update:
Removing is a static fix for the problem. I found out that the problem has nothing to do with boost or lambdas and can be reproduced when building static and using std::thread . For some reason this combination does not work. I think this post describes almost the same thing, however I don't really understand the details, and the error message is different.
Therefore, I am wondering why std::thread and static communication do not work together. Is there a reason why static communication is not allowed here? I updated the title of the question and removed the boost tag.