I am new to C++ multithreading.
I wrote a simple program to print hello world using threads.
<<mythread.cpp>>
#include<iostream>
#include<thread>
using namespace std;
void hello()
{
std::cout<<"Hi this is a thread";
}
int main()
{
std::thread mythread(hello);
cout<<'1';
if (mythread.joinable())
{
cout<<'2';
mythread.join();
cout<<'3';
}
return 0;
}
Copilation command : g++ -std=c++0x mythread.cpp
It compiled successfully but gave Segmentaion fault at run time.
I check the core file :
(gdb) bt
#0 0x0000003ac340df7c in _dl_fixup () from /lib64/ld-linux-x86-64.so.2
#1 0x0000003ac3414625 in _dl_runtime_resolve () from /lib64/ld-linux-x86-64.so.2
#2 0x0000003ac84b65c7 in std::thread::_M_start_thread(std::shared_ptr<std::thread::_Impl_base>) () from /usr/lib64/libstdc++.so.6
#3 0x00000000004010d0 in std::thread::thread<void (*)()>(void (*)()) ()
#4 0x0000000000400e15 in main ()
Kindly help me to resolve this error it seems to be some library is not supportive.
The program looks correct. Compile it with -pthread flag:
g++ -pthread -std=c++11 mythread.cpp
Related
I got a strange core dump which I copied from a part of code in http://en.cppreference.com/w/cpp/thread/packaged_task,
#include <future>
#include <iostream>
#include <cmath>
void task_lambda() {
std::packaged_task<int(int,int)> task([](int a, int b) {
return std::pow(a, b);
});
std::future<int> result = task.get_future();
task(2, 9);
std::cout << "task_lambda:\t" << result.get() << '\n';
}
int main() {
task_lambda();
}
I got this
terminate called after throwing an instance of 'std::system_error'
what(): Unknown error -1
[1] 28373 abort (core dumped) ./a.out
The call stack is like below:
#0 0x00007ffff71a2428 in __GI_raise (sig=sig#entry=6) at ../sysdeps/unix/sysv/linux/raise.c:54
#1 0x00007ffff71a402a in __GI_abort () at abort.c:89
#2 0x00007ffff7ae484d in __gnu_cxx::__verbose_terminate_handler() () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#3 0x00007ffff7ae26b6 in ?? () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#4 0x00007ffff7ae2701 in std::terminate() () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#5 0x00007ffff7ae2919 in __cxa_throw () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#6 0x00007ffff7b0b7fe in std::__throw_system_error(int) () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#7 0x0000000000404961 in std::call_once<void (std::__future_base::_State_baseV2::*)(std::function<std::unique_ptr<std::__future_base::_Result_base, std::__future_base::_Result_base::_Deleter> ()>*, bool*), std::__future_base::_State_baseV2*, std::function<std::unique_ptr<std::__future_base::_Result_base, std::__future_base::_Result_base::_Deleter> ()>*, bool*>(std::once_flag&, void (std::__future_base::_State_baseV2::*&&)(std::function<std::unique_ptr<std::__future_base::_Result_base, std::__future_base::_Result_base::_Deleter> ()>*, bool*), std::__future_base::_State_baseV2*&&, std::function<std::unique_ptr<std::__future_base::_Result_base, std::__future_base::_Result_base::_Deleter> ()>*&&, bool*&&) (__once=..., __f=<unknown type in /home/ace/test/a.out, CU 0x0, DIE 0x1246d>)
at /usr/include/c++/5/mutex:746
#8 0x0000000000403eb2 in std::__future_base::_State_baseV2::_M_set_result(std::function<std::unique_ptr<std::__future_base::_Result_base, std::__future_base::_Result_base::_Deleter> ()>, bool) (
this=0x61ec30, __res=..., __ignore_failure=false) at /usr/include/c++/5/future:387
#9 0x0000000000402b76 in std::__future_base::_Task_state<task_lambda()::<lambda(int, int)>, std::allocator<int>, int(int, int)>::_M_run(<unknown type in /home/ace/test/a.out, CU 0x0, DIE 0x17680>, <unknown type in /home/ace/test/a.out, CU 0x0, DIE 0x17685>) (this=0x61ec30, __args#0=<unknown type in /home/ace/test/a.out, CU 0x0, DIE 0x17680>,
__args#1=<unknown type in /home/ace/test/a.out, CU 0x0, DIE 0x17685>) at /usr/include/c++/5/future:1403
#10 0x00000000004051c1 in std::packaged_task<int (int, int)>::operator()(int, int) (this=0x7fffffffdca0, __args#0=2, __args#1=9) at /usr/include/c++/5/future:1547
#11 0x0000000000401c7d in task_lambda () at aa.cc:12
#12 0x0000000000401d1b in main () at aa.cc:19
Then I added some sample code into my program, it became
#include <iostream>
#include <cmath>
#include <future>
#include <thread>
int f(int x, int y) { return std::pow(x,y); }
void task_thread() {
std::packaged_task<int(int,int)> task(f);
std::future<int> result = task.get_future();
std::thread task_td(std::move(task), 2, 10);
task_td.join();
std::cout << "task_thread:\t" << result.get() << '\n';
}
void task_lambda() {
std::packaged_task<int(int,int)> task([](int a, int b) {
return std::pow(a, b);
});
std::future<int> result = task.get_future();
task(2, 9);
std::cout << "task_lambda:\t" << result.get() << '\n';
}
int main() {
task_lambda();
}
the error was gone. How can I correct the program by adding a function even though I never call it?
gcc version
gcc version 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.4)
Promgram compiled with command:
g++ -std=c++11 aa.cc -lpthread
With #fedepad's help, I got correct output by replace lpthread with pthread. But I still confused how second code work by add a dummy function!
I tried your first code snippet using the following version of g++:
g++ (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609
and compiled with the following
g++ -o test_threads test_threads.cpp -std=c++11 -pthread
and I can run the program with no problems, and getting the following output:
$ ./test_threads
task_lambda: 512
If I then use the -lpthread as you did with the following
g++ -o test_threads test_threads.cpp -std=c++11 -lpthread
I get
$ ./test_threads
terminate called after throwing an instance of 'std::system_error'
what(): Unknown error -1
[1] 7890 abort ./test_threads
So please use -pthread as a flag and not -lpthread.
This behavior is also mentioned in the following
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=59830
There's a difference between -pthread and -lpthread.
Looking at the man page for g++
-pthread
Adds support for multithreading with the pthreads library. This option sets flags for both the preprocessor and linker.
To have a look to what flags are activated for both one can check with the following:
g++ -dumpspecs | grep pthread
g++ -dumpspecs | grep lpthread
As one can clearly see, there are some preprocessor macros that are not activated if one is using -lpthread.
I have been Googling this one for a good long while now and am I'm not seeing anything quite like this, so here goes. I am trying to create a small statically-linked binary which can be easily distributed across machines on my home network. This is a pretty small project so I'm trying to keep things simple.
I am running into substantial difficulties when I statically link the pthread library on the ARM 32-bit architecture. Frustratingly, the very same code works just fine on all versions of x86. Here is my test.cpp program:
void threader( int num ) {
std::cout << "Child Thread Starting" << std::endl;
try {
throw 20;
} catch (int e) {
std::cout << "Child Thread Success" << std::endl;
}
int x = 0;
do {
x++;
} while (true);
}
int main(int argc, char *argv[]) {
std::cout << "Main Thread Starting" << std::endl;
new std::thread(&threader, 0);
try {
throw 20;
} catch (int e) {
std::cout << "Main Thread Success" << std::endl;
}
int y = 0;
do {
y++;
} while (true);
}
The idea is that the main thread starts a child thread, then tests to see if the main thread can throw an exception, then spins. Meanwhile, the child thread also tests to see if it can throw an exception, then spins. The original code throws a boost-brand exception, leading to a crash. This minimal example has identical behavior.
A successful result on x86 is as follows:
# g++ -m32 -std=c++11 -c -g test.cpp
# g++ -static -m32 *.o -o test -lrt -pthread
# ./test
Main Thread Starting
Child Thread Starting
Main Thread Success
Child Thread Success
However, on ARM, I get a variety of errors depending on how exactly I link things. For reference, I started with the simple:
$ g++ -std=c++11 -c -g test.cpp
$ g++ -static *.o -o test -lrt -pthread
$ ./test
Main Thread Starting
Child Thread Starting
Main Thread Success
Segmentation fault
The segmentation fault is not very helpful:
(gdb) bt
#0 0x00012be8 in __cxa_throw ()
#1 0x000108d0 in threader (num=0) at test.cpp:11
#2 0x00011a26 in std::_Bind_simple<void (*(int))(int)>::_M_invoke<0u>(std::_Index_tuple<0u>) (this=0xda50c) at /usr/include/c++/4.8/functional:1732
#3 0x00011950 in std::_Bind_simple<void (*(int))(int)>::operator()() (this=0xda50c) at /usr/include/c++/4.8/functional:1720
#4 0x0001190a in std::thread::_Impl<std::_Bind_simple<void (*(int))(int)> >::_M_run() (this=0xda500) at /usr/include/c++/4.8/thread:115
#5 0x0001befc in execute_native_thread_routine ()
#6 0x0004bcc2 in start_thread (arg=0x0) at pthread_create.c:335
#7 0x00071b4c in ?? ()
Backtrace stopped: previous frame identical to this frame (corrupt stack?)
When throw() is causing segmentation faults, you got problems. When I remove the "-static" flag, everything executes perfectly, as in the x86 case.
After extensive googling I found that this problem is apparently quite common. Other answers include:
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=52590
when g++ static link pthread, cause Segmentation fault, why?
And many other similar ones. The key recommendation appears to be to link with the "-Wl,--whole-archive -lpthread -Wl,--no-whole-archive" phrase. Ok, lets give it a go:
$ g++ -std=c++11 -c -g test.cpp
$ g++ -static *.o -o test -lrt -pthread -Wl,--whole-archive -lpthread -Wl,--no-whole-archive
$ ./test
Main Thread Starting
Child Thread Starting
terminate called after throwing an instance of 'Segmentation fault
Well, it gets points for being different. GDB:
(gdb) r
Starting program: ./test
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/arm-linux-gnueabihf/libthread_db.so.1".
Main Thread Starting
[New Thread 0x76ffc2d0 (LWP 30844)]
Child Thread Starting
terminate called after throwing an instance of 'int'
terminate called recursively
Thread 1 "test" received signal SIGABRT, Aborted.
0x00055266 in __libc_do_syscall ()
(gdb) bt
#0 0x00055266 in __libc_do_syscall ()
#1 0x0001ab66 in raise (sig=6) at ../sysdeps/unix/sysv/linux/pt-raise.c:35
#2 0x0005a85a in abort ()
#3 0x0004bd3c in __gnu_cxx::__verbose_terminate_handler() ()
#4 0x00026d34 in __cxxabiv1::__terminate(void (*)()) ()
#5 0x00026d50 in std::terminate() ()
#6 0x0001ca3c in __cxa_rethrow ()
#7 0x0004bd1c in __gnu_cxx::__verbose_terminate_handler() ()
#8 0x00026d34 in __cxxabiv1::__terminate(void (*)()) ()
#9 0x00026d50 in std::terminate() ()
#10 0x0001c9fc in __cxa_throw ()
#11 0x0001098e in main (argc=1, argv=0x7efff704) at test.cpp:28
(gdb) frame 11
#11 0x0001098e in main (argc=1, argv=0x7efff704) at test.cpp:28
28 throw 20;
(gdb)
Two things to note: one, it is now the parent thread which is crashing, and two, it is apparently an 'int' which is segfaulting. Ok... that's special.
There is another answer on SO which seems to note something similar to this:
GCC: --whole-archive recipe for static linking to pthread stopped working in recent gcc versions
But this solution recommends jiggering around the order and frequency of the -lrt and -lpthread flags. I have tried... a great many combinations of these. It always results in the above behavior.
I will also note that the example program in the above issue runs perfectly fine on the problem ARM32 system. However, it immediately breaks if I add the "throw 20" test block to the thread function.
For the record, I have also tried many combinations with boost::thread and have also tried compiling with clang, all to the same results.
At this point I am at a complete loss and throw myself on the mercies of the internet. Does anyone have any idea what is going on here, or how I can investigate more?
My program crashes with a segfault trying to unwind the stack. Is this a gcc bug or is the combination of options -fexceptions and -static-libgcc not allowed?
The crash doesn't happen if:
-static-libgcc is omitted
-fexceptions is omitted
Compile and link are done in a single step
pthread_cleanup_push() and pthread_cleanup_pop() are omitted
Compilation is done using g++ or gcc -x g++ (*)
I have tried this on gcc 4.8.4 and 4.8.5.
(*) This doesn't work for one of our custom build environments based on gcc 4.2.3. Yet for a different version of the build environment also based on gcc 4.2.3 the crash doesn't happen at all!
Test case
/*
* thread_crash.c: Test case for thread unwinder crash bug.
*
* Compile (with native or V6p3, 32 or 64 bit) using:
* gcc -o thread_crash.o -c thread_crash.c -ggdb -Wall -pthread -fexceptions
* g++ -o thread_crash thread_crash.o -ggdb -Wall -lpthread -static-libgcc
*
* Expected behaviour: No output.
* Observed behaviour: Outputs "Aborted (core dumped)".
*/
#include <unistd.h>
#include <pthread.h>
#include <sys/types.h>
#include <signal.h>
static void cleanup(void *ptr)
{
}
void *child(void *ptr)
{
pthread_cleanup_push(cleanup, NULL);
pthread_exit(NULL);
pthread_cleanup_pop(1);
return NULL;
}
int main()
{
pthread_t foo;
pthread_create(&foo, NULL, child, NULL);
pthread_join(foo, NULL);
return 0;
}
Backtrace from gdb
#0 0x00007ffff72271f7 in raise () from /lib64/libc.so.6
#1 0x00007ffff72288e8 in abort () from /lib64/libc.so.6
#2 0x00000000004031be in _Unwind_SetGR ()
#3 0x000000000040587a in __gcc_personality_v0 ()
#4 0x00007ffff6feba14 in ?? () from /lib64/libgcc_s.so.1
#5 0x00007ffff6febd64 in _Unwind_ForcedUnwind () from /lib64/libgcc_s.so.1
#6 0x00007ffff7bcd240 in __pthread_unwind () from /lib64/libpthread.so.0
#7 0x00007ffff7bc7e35 in pthread_exit () from /lib64/libpthread.so.0
#8 0x0000000000400a97 in child (ptr=0x0) at thread_crash.c:46
#9 0x00007ffff7bc6e25 in start_thread () from /lib64/libpthread.so.0
#10 0x00007ffff72ea34d in clone () from /lib64/libc.so.6
When compiling with -fexception, pthread_exit() throws a ___forced_unwind exception to force all functions to be unwinded, this guarantees automatic storage (aka stack) cleanup. This is because pthread_exit() is designed not to return. From man pthread_exit:
This function does not return to the caller.
On the other hand, according to man pthread_cleanup_push:
POSIX.1 says that the effect of using return, break, continue, or
goto to prematurely leave a block bracketed pthread_cleanup_push()
and pthread_cleanup_pop() is undefined. Portable applications should
avoid doing this.
POSIX does not mention C++ exceptions since POSIX only care about C, but this is an educated guess that throwing an exception between pthread_cleanup_push() and pthread_cleanup_pop() results in an undefined behaviour.
I got a strange core dump which I copied from a part of code in http://en.cppreference.com/w/cpp/thread/packaged_task,
#include <future>
#include <iostream>
#include <cmath>
void task_lambda() {
std::packaged_task<int(int,int)> task([](int a, int b) {
return std::pow(a, b);
});
std::future<int> result = task.get_future();
task(2, 9);
std::cout << "task_lambda:\t" << result.get() << '\n';
}
int main() {
task_lambda();
}
I got this
terminate called after throwing an instance of 'std::system_error'
what(): Unknown error -1
[1] 28373 abort (core dumped) ./a.out
The call stack is like below:
#0 0x00007ffff71a2428 in __GI_raise (sig=sig#entry=6) at ../sysdeps/unix/sysv/linux/raise.c:54
#1 0x00007ffff71a402a in __GI_abort () at abort.c:89
#2 0x00007ffff7ae484d in __gnu_cxx::__verbose_terminate_handler() () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#3 0x00007ffff7ae26b6 in ?? () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#4 0x00007ffff7ae2701 in std::terminate() () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#5 0x00007ffff7ae2919 in __cxa_throw () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#6 0x00007ffff7b0b7fe in std::__throw_system_error(int) () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#7 0x0000000000404961 in std::call_once<void (std::__future_base::_State_baseV2::*)(std::function<std::unique_ptr<std::__future_base::_Result_base, std::__future_base::_Result_base::_Deleter> ()>*, bool*), std::__future_base::_State_baseV2*, std::function<std::unique_ptr<std::__future_base::_Result_base, std::__future_base::_Result_base::_Deleter> ()>*, bool*>(std::once_flag&, void (std::__future_base::_State_baseV2::*&&)(std::function<std::unique_ptr<std::__future_base::_Result_base, std::__future_base::_Result_base::_Deleter> ()>*, bool*), std::__future_base::_State_baseV2*&&, std::function<std::unique_ptr<std::__future_base::_Result_base, std::__future_base::_Result_base::_Deleter> ()>*&&, bool*&&) (__once=..., __f=<unknown type in /home/ace/test/a.out, CU 0x0, DIE 0x1246d>)
at /usr/include/c++/5/mutex:746
#8 0x0000000000403eb2 in std::__future_base::_State_baseV2::_M_set_result(std::function<std::unique_ptr<std::__future_base::_Result_base, std::__future_base::_Result_base::_Deleter> ()>, bool) (
this=0x61ec30, __res=..., __ignore_failure=false) at /usr/include/c++/5/future:387
#9 0x0000000000402b76 in std::__future_base::_Task_state<task_lambda()::<lambda(int, int)>, std::allocator<int>, int(int, int)>::_M_run(<unknown type in /home/ace/test/a.out, CU 0x0, DIE 0x17680>, <unknown type in /home/ace/test/a.out, CU 0x0, DIE 0x17685>) (this=0x61ec30, __args#0=<unknown type in /home/ace/test/a.out, CU 0x0, DIE 0x17680>,
__args#1=<unknown type in /home/ace/test/a.out, CU 0x0, DIE 0x17685>) at /usr/include/c++/5/future:1403
#10 0x00000000004051c1 in std::packaged_task<int (int, int)>::operator()(int, int) (this=0x7fffffffdca0, __args#0=2, __args#1=9) at /usr/include/c++/5/future:1547
#11 0x0000000000401c7d in task_lambda () at aa.cc:12
#12 0x0000000000401d1b in main () at aa.cc:19
Then I added some sample code into my program, it became
#include <iostream>
#include <cmath>
#include <future>
#include <thread>
int f(int x, int y) { return std::pow(x,y); }
void task_thread() {
std::packaged_task<int(int,int)> task(f);
std::future<int> result = task.get_future();
std::thread task_td(std::move(task), 2, 10);
task_td.join();
std::cout << "task_thread:\t" << result.get() << '\n';
}
void task_lambda() {
std::packaged_task<int(int,int)> task([](int a, int b) {
return std::pow(a, b);
});
std::future<int> result = task.get_future();
task(2, 9);
std::cout << "task_lambda:\t" << result.get() << '\n';
}
int main() {
task_lambda();
}
the error was gone. How can I correct the program by adding a function even though I never call it?
gcc version
gcc version 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.4)
Promgram compiled with command:
g++ -std=c++11 aa.cc -lpthread
With #fedepad's help, I got correct output by replace lpthread with pthread. But I still confused how second code work by add a dummy function!
I tried your first code snippet using the following version of g++:
g++ (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609
and compiled with the following
g++ -o test_threads test_threads.cpp -std=c++11 -pthread
and I can run the program with no problems, and getting the following output:
$ ./test_threads
task_lambda: 512
If I then use the -lpthread as you did with the following
g++ -o test_threads test_threads.cpp -std=c++11 -lpthread
I get
$ ./test_threads
terminate called after throwing an instance of 'std::system_error'
what(): Unknown error -1
[1] 7890 abort ./test_threads
So please use -pthread as a flag and not -lpthread.
This behavior is also mentioned in the following
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=59830
There's a difference between -pthread and -lpthread.
Looking at the man page for g++
-pthread
Adds support for multithreading with the pthreads library. This option sets flags for both the preprocessor and linker.
To have a look to what flags are activated for both one can check with the following:
g++ -dumpspecs | grep pthread
g++ -dumpspecs | grep lpthread
As one can clearly see, there are some preprocessor macros that are not activated if one is using -lpthread.
When debugging a program that fails an assert I can't get the call stack in gdb. I'm using g++4.8 and gdb from Homebrew on Mavericks.
/usr/local/bin/g++-4.8 --version
g++-4.8 (GCC) 4.8.2
/usr/local/bin/gdb --version
GNU gdb (GDB) 7.6.2
Here is the smallest test to reconstruct the problem
//test.cpp
#include <iostream>
#include <cassert>
int main()
{
int i = 42;
std::cout << "Hello World!" << i << std::endl;
assert(0); // this also happens with abort() which assert(0) winds up calling
}
Compiling and with
/usr/local/bin/g++-4.8 -g -c test.cpp -o test.o
/usr/local/bin/g++-4.8 -g test.o -o test
/usr/local/bin/gdb test
(gdb) r
Starting program: /Users/pmelsted/tmp/test/test
Hello World!42
Assertion failed: (0), function main, file test.cpp, line 7.
Program received signal SIGABRT, Aborted.
0x00007fff9447d866 in ?? ()
(gdb) where
#0 0x00007fff9447d866 in ?? ()
#1 0x00007fff9229835c in ?? ()
#2 0x0000000000000000 in ?? ()
It seems gdb on MacOS don't display call stack correctly (or call stack is corrupted after assert() function call) for 64-bit programs. Here is the program slightly modified:
//test.cpp
#include <iostream>
#include <cassert>
int foo() {
assert(0);
}
int bar() {
return foo();
}
int main()
{
int i = 42;
std::cout << "Hello World!" << i << std::endl;
return bar();
}
I have compiled it invoking the g++ -g 15.cpp -m32 command and have ran it under ggdb. The bt full command shows call stack as the following:
(gdb) bt full
#0 0x9843f952 in ?? ()
No symbol table info available.
#1 0x96193340 in ?? ()
No symbol table info available.
#2 0x9615e43e in ?? ()
No symbol table info available.
#3 0x0000216f in foo () at 15.cpp:6
No locals.
#4 0x0000217b in bar () at 15.cpp:9
No locals.
#5 0x000021e4 in main () at 15.cpp:15
i = 42
(gdb) quit
So, all debug symbols are displayed correctly, first 3 function addresses are corrected and have no name because my libgcc is in release mode.
If I don't use -m32 key during compilation, the call stack is as follows:
(gdb) bt full
#0 0x00007fff8b442866 in ?? ()
No symbol table info available.
#1 0x00007fff8c64735c in ?? ()
No symbol table info available.
#2 0x0000000000000000 in ?? ()
No symbol table info available.
That is definitely wrong call stack, #2 frame function address is 0x0. So, the root cause is gdb can't display call stack correctly for 64-bit applications.
I found a workaround for the problem. Just set the breakpoint to abort() function in gdb:
b abort
then when assert is called it will halt at the breakpoint and at this moment one can see the call stack with bt.