Starting a std::thread with static linking causes segmentation fault - c++

To learn c++11 (and boost) I am writing a simple http-server using boost asio and c++11 (for threading and lambdas).
I want to test the new c++11 lambdas and std::thread so I tried to start the io_service.run() like this in a std::thread with a 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 terminates with segmentation fault. Additionally sometimes it is running the cout inside the lambda, sometimes not (although endl should flush). In any case, it prints the correct address of io_service_. However, when I replace the std::thread with a boost::thread (no other change!), everything is working fine.
I would appreciate it if anyone has an idea where the problem is caused (could be asio, std::thread or std::lambda).
Additional information:
According to another post accessing the member io_service_ within a lambda is fine when capturing this, as I do it.
I am running gcc 4.6.1 on Ubuntu and boost 1.46. G++ parameters:
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 -static fixed the problem. I found out that the problem has nothing to do with boost or lambdas and can be reproduced whenever building static and using std::thread. For any reason this combination does not work.
I think this post describes almost the same, however I don't really understand the details and the error message is different.
So I wonder why std::thread and static linking don't seem to work together. Is there a reason why static linking is not allowed here? I updated the question title and removed the boost tag.

Link your app with -Wl,--whole-archive -lpthread -Wl,--no-whole-archive
More here https://gcc.gnu.org/bugzilla/show_bug.cgi?id=52590
It works for me.

Removing -static solved the problem. I found out that it has nothing to do with boost or lambdas, but with static linking and std::thread, which don't seem to work together for any unknown reason (see also this post that might be related).
I guess the question why they don't work together is - though interesting - out of scope for now, and I am glad with the answer, so this can be marked as answered.

Related

Program doesn't start when linking boost filesystem

I'm trying to run a helloworld program which uses boost filesystem.
I'm on Windows with MinGW 8.1 and boost 1.70.
The problem is that, although everything compiles, the program doesn't run. I mean, it runs but doesn't print anything, which means the main function is not even executed:
#include <boost/filesystem.hpp>
#include <iostream>
using namespace std;
using namespace std::string_literals;
namespace fs = boost::filesystem;
int main()
{
cout << "Hello Boost!" << endl;
fs::path abHome{"C:/Users/Me"s};
fs::path jsonFile = abHome / "jsonFile.json"s;
if (!fs::exists(jsonFile)) {
cout << "Creating json file from scratch." << endl;
}
}
"Hello Boost" isn't ever printed to the console.
I've compiled with both CMake and g++ from command line to try to better understand what's going on:
g++ main.cpp -o main -L"C:/Code/boost_1_70_0/stage/lib" -lboost_filesystem-mgw81-mt-x64-1_70 -lboost_system-mgw81-mt-x64-1_70 -I"C:/Code/boost_1_70_0"
I've compiled boost for MinGW by following the guide and everything went well, in the output folder I see many different versions of each library based on the default targets (I haven't really picked them, just went with the defaults).
How can I debug the launch of main.exe to see what's causing the crash? It's been many years since I wrote C++ so I need help to get back on track! :)
The problem was, as #kenba pointed out, that the dynamic linking of the boost dlls was failing.
I erroneously thought I had linked the static version of the boost libraries.
To actually achieve that I should have used this command:
g++ main.cpp -o main -L"C:/Code/boost_1_70_0/stage/lib" -l:"libboost_filesystem-mgw81-mt-x64-1_70.a" -l:"libboost_system-mgw81-mt-x64-1_70.a" -I"C:/Code/boost_1_70_0"
instead of the one I posted in the OP.

How do I compile a cpp file with the thread class? [duplicate]

This question already has an answer here:
Does MinGW-w64 support std::thread out of the box when using the Win32 threading model?
(1 answer)
Closed 4 years ago.
I am learning to use threading so I am trying to run code utilizing the thread class so that I can run functions concurrently. However, trying to compile it in the terminals terminal, it says that thread and its object t1 is not declared.
threading.cpp:16:5: error: 'thread' was not declared in this scope
thread t1(task1, "Hello");
^~~~~~
threading.cpp:21:5: error: 't1' was not declared in this scope
t1.join();
I thought g++ doesn't support it but I also include in its argument to support c++11
g++ -std=c++11 threading.cpp
Any idea what I should I do about this error?
(OS: windows, gcc version 6.3.0)
Code is provided below(an example from a website):
#include <string>
#include <iostream>
#include <thread>
using namespace std;
// The function we want to execute on the new thread.
void task1(string msg)
{
cout << "task1 says: " << msg;
}
int main()
{
// Constructs the new thread and runs it. Does not block execution.
thread t1(task1, "Hello");
// Do other things...
// Makes the main thread wait for the new thread to finish execution, therefore blocks its own execution.
t1.join();
}
Any idea what I should I do about this error?
Your code compiles and runs fine with a recent version of GCC (coliru.com). And the same is true for older versions (e.g. GCC 6) and with -std=c++11. Your problem must be elsewhere:
Perhaps you're using an extremely old compiler?
Perhaps your C++ standard library headers are not installed?
Perhaps your C++ standard library headers are located someplace unexpected? That could happen if you're using a custom-installed version of the compiler or standard library.

How do I setup my g++ compiler for C++11? [duplicate]

This question already has answers here:
Closed 10 years ago.
I tried a basic program:
// ThreadExample.cpp
#include <string>
#include <iostream>
#include <thread>
using namespace std;
void task1(string msg)
{
cout << "task1 says: " << msg;
}
int main()
{
thread t1(task1, "Hello");
t1.join();
}
One I actually found on stackoverflow, but I tried compiling it using:
g++ -std=c++0x -pthread ThreadExample.cpp -o ThreadExample -lm
However, I keep getting an error that thread is undeclared. I have version 4.7.1 of the MinGW GNU for Windows. Is there something I can change so I can use C++11?
Noone has contributed an implementation of <thread>, <mutex> etc for Mingw yet, except when using Mingw with (optional) Pthreads support via a third-party pthreads implementation.
I started a thread at http://gcc.gnu.org/ml/libstdc++/2012-05/msg00020.html with some suggestions for implementing the missing features in terms of Windows native threads, but as I don't have a Windows machine and noone else has volunteered to do anything, nothing happened. I have almost zero interest in implementing it myself, because I never develop for Windows so it would be of no use to me whatsoever, and I would rather spend my limited free time implementing things I will actually use. If anyone wants to work on it I'd happily advise them and review their code and help shepherd it into GCC.

C++ sleep pthread conflict

I am writing a code about the deadlocks and their detection, i use eclipse Juno C/C++ on Ubuntu 12.10, 64 bit.
The problem is when i use
sleep(1)
, i get this
sleep was not declared in this scope
when i build the project, i tried to include
include < unistd.h>
, but then all the pthread functions like
pthread_join
gives me errors like
undefined reference to pthread_join
, without #include < unistd.h> such error doesn't show up.
sample code:
#include <unistd.h>
#include <iostream>
#include <semaphore.h>
#include <queue>
#include <stdlib.h>
using namespace std;
pthread_mutex_t mutex;
sem_t sem; //used for writing in the console
.......
void cross(Batman b) {
// code to check traffic from the right, use counters, condition
sem_wait(&sem);
cout << "BAT " << b.num << " from " << b.direction << " crossing" << endl;
sem_post(&sem);
sleep(1);
}
........
p.s. i followed these instructions to get pthreads working in other project and i did the same for this project
http://blog.asteriosk.gr/2009/02/15/adding-pthread-to-eclipse-for-using-posix-threads/
p.s. i am working on this project with a friend and i used the same code he uses and still get those errors, while he doesn't
when you #include < unistd.h>, you fixed sleep function look up issue, now you have pthread library issue.
Next you need to #include <pthread.h> and link your application with pthread library
It sounds like you have two different errors,
first sleep() is undefined because you forgot to include unistd.h. I'd also include pthread.h but it sounds like it might get pulled in by one of the headers you include.
Secondly it sounds like you have a linker error add, you can either compile with -pthread or add -lpthread to the linker. The reason it doesn't show up is because linking can only be done once the files have been compiled and the first error is blocking this. I'd bet that ld doesn't like -pthread for some reason (have you installed libpthread-dev?). You can try changing -pthread to -lpthread.

Code Blocks, MinGW, Boost, and static linking issues

I am using Code Blocks with MinGW and am trying to get a simple program to compile with static linking. I have built the Boost libraries using these directions. Everything worked out fine and I was able to successfully compile this simple program (it compiles, I know it doesn't work because it exits before the message is sent to the console, but I just want it to compile).
If I have a DLL in my linker libraries, it compiles fine, but when I switch it with the static .a libraries of the same contents, I get undefined references such as "undefined reference to `_imp___ZN5boost6threadD1Ev'|".
I have no idea what the problem is and can't find the solution. I think it might have to do with linker settings but I can't find information on how to change them. I would be extremely grateful for any help that could be provided.
#include <iostream>
#include <boost/thread.hpp>
void myfunction()
{
std::cout << "this is a thread" << std::endl;
return;
}
int main()
{
boost::thread mythread(&myfunction);
return 0;
}
It's from trying to link statically when the headers are configured for a dynamic link. I explain this for libssh in this question. Poking around in boost/thread/detail/config.hpp makes me think you should #define BOOST_THREAD_USE_LIB, or use the -D flag to do the same.