the following program give some strange compile/run-time behavior when compiled with Visual Studio 2013:
#include "stdafx.h"
#include <thread>
#include <chrono>
#include <iostream>
int main()
{
{//works
std::thread([](){
std::cout << " thread running1\n";
});
}
{//compile but synstax error exist
auto func = [](){
std::cout << " thread running2\n";
};
std::thread(fun); //fun is not defined
}
{//compile, see next block for mystery compile error
auto func = [](){
std::cout << " thread running2\n";
};
std::thread tmp(func);
}
{//does not compile and don't know why
auto func = [](){
std::cout << " thread running2\n";
};
std::thread(func); //error C2371: 'func' : redefinition; different basic types
}
return 0;
}
When this program work, there may crash as there is race condition between the thread. The main thread may end before the other threads.
Does anybody know why the second block and last block does not work?
{//compile but synstax error exist
auto func = [](){
std::cout << " thread running2\n";
};
std::thread(fun); //fun is not defined
}
There's no syntax error here, std::thread(fun) default constructs an std::thread object named fun.
The error in the last block is because of the same reason
std::thread(func); //error C2371: 'func' : redefinition; different basic types
You're trying to default construct an std::thread object named func above and that's an error because a lambda of the same name already exists in the same scope. To pass the lambda to the thread constructor use braces instead
std::thread{func};
Now, after you've made these changes your code will compile but will fail at runtime because the thread objects in blocks 1, 3 & 4 are all going to call std::terminate (of course, your program terminates when the first thread object calls std::terminate so the other two doing that is a moot point).
The reason that happens is that you have joinable threads in all 3 blocks and if the destructor of such a thread object runs, std::terminate will be called. To avoid that you must call thread::join (you could also call thread::detach but don't do that).
For instance
{//works
std::thread([](){
std::cout << " thread running1\n";
}).join();
}
Live demo
Related
I'm using LibJIT to JIT-compile a programming language. My compiler is written in C++, so I have a C++ program calling the LibJIT library, which is written in C.
In my C++ code I have some functions that throw exceptions, and sometimes these get triggered on the far side of a LibJIT-compiled function. That is, my C++ program uses LibJIT to compile a function, calls it, and the JIT-compiled function in turn calls a C++ function that throws an exception. But instead of the exception being propagated back through the JIT-compiled function to my handler, the runtime calls std::terminate.
Apparently the exception-handling mechanism needs each function in the call stack to implement some kind of exception support. When compiling C code, the -fexceptions flag tells the compiler (at least gcc) to include this support.
Is there a way to include this exception support in my LibJIT-generated functions?
I tried using the LibJIT instructions to set up a "catcher" block that rethrows all exceptions, but that didn't work; it looks like the LibJIT's exception-handling model is separate from the C++ model.
Obviously I don't really want to throw C++ exceptions into my language's code, and I'll have to figure out some other error-handling strategy. But I'm wondering if it's even possible to get it to work.
Here's a sample program that demonstrates the issue. I'm sorry it's this long but LibJIT is pretty low-level so you have to write a lot of code to get anything done. I'm compiling on Linux with clang 10.0.0.
#include <array>
#include <exception>
#include <iostream>
#include <string>
#include <jit/jit.h>
class ex : public std::exception {};
extern "C" int bad(int arg) {
std::cout << "Called with arg=" << arg << std::endl;
throw ex();
}
jit_function_t build_function(jit_context_t context) {
// The signature of the compiled function and "bad" are the same.
std::array<jit_type_t, 1> params{jit_type_int};
jit_type_t signature = jit_type_create_signature(jit_abi_cdecl, jit_type_int, params.data(), params.size(), 1);
jit_function_t function = jit_function_create(context, signature);
jit_value_t arg_value = jit_value_get_param(function, 0);
jit_value_t bad_value =
jit_value_create_nint_constant(function, jit_type_void_ptr, (reinterpret_cast<jit_nint>(bad)));
std::array<jit_value_t, 1> bad_args{arg_value};
jit_value_t result = jit_insn_call_indirect(function, bad_value, signature, bad_args.data(), bad_args.size(), 0);
jit_insn_return(function, result);
jit_function_compile(function);
return function;
}
int main(int argc, char* argv[]) {
// This exception will be caught:
try {
bad(7);
} catch (const ex&) {
std::cout << "Caught exception from direct call" << std::endl;
}
// Initialize libjit.
// We're single-threaded so not going to bother with jit_context_build_start/jit_context_build_end.
jit_init();
jit_context_t context = jit_context_create();
jit_function_t function = build_function(context);
// This one will not be caught, calls std::terminate instead:
try {
int (*closure)(int) = reinterpret_cast<int (*)(int)>(jit_function_to_closure(function));
closure(7);
} catch (const ex&) {
std::cout << "Caught exception from libjit call" << std::endl;
}
return 0;
}
Output:
Called with arg=7
Caught exception from direct call
Called with arg=7
terminate called after throwing an instance of 'ex'
what(): std::exception
Aborted
The following code causes bus error in Rasbian distro on a rasberry pi mod2 system.
#include <thread>
#include <iostream>
class bar {
public:
void startFoo() {
std::thread t(&bar::foo, this); //bus error because of this line
t.join();
}
void foo() {
std::cout << "hello from member function" << std::endl;
}
};
int main()
{
bar b;
b.startFoo();
return 0;
}
This link states that bus error occurs when your processor cannot even attempt the memory access requested. But in my code i am accessing the class own member function in thread. I cannot relate how it is causing bus error. Could someone clarify me? P.S. The source code was cross compiled on a Ubuntu OS running on a x86 PC and the binary was tested on Rasberry pi (ARM).
i got a minimal example from http://www.cplusplus.com/reference/thread/thread/
for the implementation of threads.
Unfortunately this example did not compile and ERROR C2664 is thrown:
// thread example
#include <iostream> // std::cout
#include <thread> // std::thread
void foo()
{
// do stuff...
}
void bar(int x)
{
// do stuff...
}
int main()
{
std::thread first (foo); // spawn new thread that calls foo()
std::thread second (bar,0); // spawn new thread that calls bar(0)
std::cout << "main, foo and bar now execute concurrently...\n";
// synchronize threads:
first.join(); // pauses until first finishes
second.join(); // pauses until second finishes
std::cout << "foo and bar completed.\n";
return 0;
}
error C2664: 'std::thread::thread(const std::thread &)' :
cannot convert argument 1 from 'void' to 'std::thread &&'
Can someone explain what ist wrong with the example // with Visual Studio?
Thanks
The above code works in VS 2013 (but also in VS 2012, VS 2015).
Try to create a new project and copy the code there. VS behaves strange sometimes. Also removing the .sdf file may help together with "build -> clean solution".
While reviewing bit of code, I came across a buggy std::terminate() handler
that wasn't terminating the program, but returning. Based on the documentation for std::set_terminate(), I think this falls within the realms of undefined - or at least implementation defined - behaviour.
Under Linux, and compiled using GCC, I found that cores were being dumped, which implies that some guardian angel was calling abort() or something similar on our behalf.
So I wrote the following test snippet, which confirmed my hunch. It looks like GCC or it's std library does wrap std::terminate() handlers so they do terminate the program.
#include <iostream>
#include <exception>
#include <dlfcn.h>
// Compile using
// g++ main.cpp -ldl
// Wrap abort() in my own implementation using
// dlsym(), so I can see if GCC generates code to
// call it if my std::terminate handler doesn't.
namespace std
{
void abort()
{
typedef void (*aborter)();
static aborter real_abort = 0x0;
if (0x0 == real_abort)
{
void * handle = 0x0;
handle = dlsym(RTLD_NEXT, "abort");
if (handle)
{
real_abort = (aborter )(handle);
}
}
std::cout << "2. Proof that GCC calls abort() if my buggy\n"
<< " terminate handler returns instead of terminating."
<< std::endl;
if (real_abort)
{
real_abort();
}
}
}
// Buggy terminate handler that returns instead of terminating
// execution via abort (or exit)
void buggyTerminateHandler()
{
std::cout << "1. In buggyTerminateHandler." << std::endl;
}
int main (int argc, char ** argv)
{
// Set terminate handler
std::set_terminate(buggyTerminateHandler);
// Raise unhandled exception
throw 1;
}
That a compiler (or library) would wrap std::terminate() handlers seems sensible to be, so at a guess I'd assume that most compilers do something along these lines.
Can anyone advise regarding the behaviour on Windows using Visual Studio or OS X using GCC?
I'm following some tutorials by Bartosz Milewski here which I find very useful.
However, as the author uses the just::thread implementation of the C++11 threading standard (which I don't yet have), I have decided to go with boost threads for now as the author of the tutorial says its trivial to do so. This seems to be the case for the first three tutorials in the series but I bumped into some problems with the fourth. Here is my code:
#include <iostream>
#include <cassert>
#include <boost\thread.hpp>
#include <boost\thread\future.hpp>
void thFun(boost::promise<std::string> & prms)
{
std::string str("Hi from future!");
prms.set_value(str);
}
int main()
{
boost::promise<std::string> prms;
boost::unique_future<std::string> fut = prms.get_future();
boost::thread th(&thFun, std::move(prms)); // error C2248: 'boost::promise<R>::promise' : cannot access private member declared in class 'boost::promise<R>'
std::cout << "Hi from main!";
std::string str = fut.get();
std::cout << str << std::endl;
th.join();
return 0;
}
The following line seems to raise an issue that I don't understand:
boost::thread th(&thFun, std::move(prms));
where the compiler complains:
error C2248: 'boost::promise::promise' : cannot access private
member declared in class 'boost::promise'
Can anyone suggest what the problem might be?
thanks in advance!
boost::thread uses boost::bind to handle a thread function with additional arguments, which requires that they are copyable. You could pass the promise by pointer or reference (using e.g. boost::ref), but that requires that the object outlives the thread. In this example it is OK, but for a detached thread, or one which outlives the function that started it, this would prevent the use of boost::promise objects on the stack.