c++ simple start a function with its own thread - c++

i had once had a very simple one or two line code that would start a function with its own thread and continue running until application closed, c++ console app. lost the project it was in, and remember it was hard to find. cant find it online now. most example account for complicated multithreading situations. but i just need to open this one function in its own thread. hopefully someone knows what im talking about, or a similar solution.
eg.
start void abc in its own thread, no parameters

An example using C++11 thread support:
#include <thread>
void abc(); // function declaration
int main()
{
std::thread abcThread(abc); // starts abc() on a separate thread
....
abcThread.join(); // waits until abcThread is done.
}
If you have no C++11 support, the same is possible using boost::thread, just by replacing std::thread by boost::thread.

Related

Is there a way to raise a compile time error when calling a given function several times in C++?

Is there a way in C++ to design a function / add some "attributes" to it in such a way that calling it several times in the code would raise a compile time error?
To give a bit of background / motivation: I was programming on Mbed-OS and I did a couple of mistakes that look like:
rtos::Thread thread;
[lots of code]
thread.start(persistent_function_1);
[lots of code in a setup function]
thread.start(persistent_function_2);
This had the (logical) consequence that the persistent_function_1, which should have been allowed to execute for the lifetime of the program, only got to execute until the thread was re-purposed to run persistent_function_2. It took me a long time to find this bug, and I was wondering if I can do something to my thread.start function to make sure I get a compiler error if I make this sort of mistake again.
I don't think there is a way to coerce the C++ language directly to detect double invocation of start() at compile time (put differently, I don't think #user4581301's suggestion would work): to statically assert a property you'd need to somehow change the entity. I'm sure you could write a custom checker using clang but I guess that isn't what you are after. It would, obviously, be possible to have a run-time assertion which reports that an already start()ed thread is started again. Again, that doesn't seem to be what you are after.
The "obvious" solution is no to have "[lots of code]" in a function to start with. In fact, std::thread entirely side-steps that issue by enforcing that there is no code between the object declaration and its start: the std::thread is started upon construction. The setup with "[lots of code]" between the object declaration and the start would be something like
my::thread thread([&]{
[lots of code]
return persistent_function_1;
}());
The caveat is that you'd need to set up your various variables sort of out of order. That is, the preferred approach would be to declare the thread object at the site where it is actually started:
[lots of code]
my::thread thread(persistent_function_1);
In both of these cases my::thread would be a trivial wrapper around rtos::thread which doesn't expose a separate start() method. As I don't know why rtos::thread separates construction and start() and a plausible reason could be the ability to set up various thread parameters, it may be reasonable to actually use two separate arguments to my::thread's constructor:
A function taking a my::thread::properties entity as parameter which allows the necessary manipulations of the thread object.
The function to be started.
That is, something like
my::thread thread([](my::thread::properties& properties) {
[lots of code manipulating the properties]
},
persistent_function_1);
This way, it remains possible to manipulate the thread but you can't possible start() a thread twice.
One option is to wrap the thread in a new manager object, with the rough shape of
class thread_manager {
rtos::Thread thread;
const std::function<...> execution_function;
/* .
.
. */
public:
thread_manager(rtos::Thread _thread, std::function<...> function, ...)
: thread { _thread }
, execution_function { function }
, ...
void start();
}
and disallowing any other usage of threading (which can be justified on the basis of encapsulation, although as pointed out in comments, yahoos are always a risk).
There is no current mechanism for detecting an expression that appears twice. But you can torture the compiler to get something close
namespace
{
template<int>
struct once
{
once() {}
friend void redefine() {}
};
}
#define ONCE(expr) (once<__COUNTER__>{}, (expr))
If ONCE ever appear twice in the same TU, the compiler will complain about redefining redefine.
ONCE(thread.start(persistent_function_1)); // ok
ONCE(thread.start(persistent_function_2)); // error

Xcode 7: C++ threads ERROR: Attempting to use a deleted function

I have been writing a sudoku solver in c++ on Xcode 7. I managed to write a successful solver using a backtracking algorithm.
Now i'm trying to parallelize whatever functions inside my solver so that I can to speed up the solving algorithm. I have 3 functions that are in charge of checking if the current number trying to be inserted into the grid exists in the row, column or box. (standard sudoku rules). Since these are mutually exclusive operations I want to parallelize them.
I know it's overkill to multithread this program, but the goal is more to learn multithreading rather than speed up my solver algorithm.
This is what I've got so far.
I've included the standard c++11 thread library.
Using default Xcode 7 build settings.
The error I get says that I'm attempting to use a deleted function which pops up when I hit the "Build and Run" button on Xcode. Xcode's intellisense does not complain bout my code. I don't understand this. Please help.
#include <thread>
....
typedef uint8_t byte;
typedef uint16_t dbyte;
....
bool sudokuGame::check(byte num, byte row, byte col)
{
setBoxFlag(true);
setColFlag(true);
setRowFlag(true);
std::thread t1{&sudokuGame::checkRow, num, row};
std::thread t2{&sudokuGame::checkColumn,num,col};
std::thread t3{&sudokuGame::checkBox,num,row,col};
t1.join();
t2.join();
t3.join();
return (getBoxFlag() && getRowFlag() && getColFlag());
}
Somewhere inside "thread" where the "attempting to use a deleted function" ERROR pops up.
...
__thread_execute(tuple<_Fp, _Args...>& __t, __tuple_indices<_Indices...>)
{
__invoke(_VSTD::move(_VSTD::get<0>(__t)), _VSTD::move(_VSTD::get<_Indices>(__t))...);
}
...
My build settings looks like this
To create a thread using non-static member functions, you need to provide the instance the member function should use, the this variable inside the thread function. This is done by passing the instance as the first argument to the thread function:
std::thread t1{&sudokuGame::checkRow, this, num, row};
// ^^^^
// Note the use of `this` here
Note that you don't need to change the thread function, it's all handled by the standard library and the compiler.
Then for another problem: The thread assignments like
t1=std::thread(&sudokuGame::checkRow, num, row);
They don't make any sense. You have already created the thread objects, initialized them, and got the thread running. And because the threads are already running you can't assign to them. See e.g this reference for the overloaded thread assignment operator.
The compiler error you get is because of the first problem, that you don't pass an instance when creating the threads.

V8-code in another pthread brings to segfault

Why this code brings to SEGFAULT?:
int jack_process(jack_nframes_t nframes, void *arg)
{
Local<Value> test = Local<Value>::New( Number::New(2) );
return 0;
}
jack_process is running in another pthread. How I can do it right way? How I can run V8 code in another pthread?
Note, this code has no any segfaults.
int jack_process(jack_nframes_t nframes, void *arg)
{
Local<Value> test;
return 0;
}
Thanks.
JavaScript and Node are single threaded. By running that code in another thread, you are essentially trying to run two threads of JS at the same time.
V8 allows you to run two JS instances on threads, but they need to be totally independent Isolate instances.
Generally C++ code written in another thread will just use standard C++ classes and variables, and then use libuv's threading support via uv_async_send, and then the async handler in the main thread will convert the values into V8 objects for JS processing.

Asynchronous call to MATLAB's engEvalString

Edit 2: Problem solved, see my answer.
I am writing a C++ program that communicates with MATLAB through the Engine API. The C++ application is running on Windows 7, and interacting with MATLAB 2012b (32-bit).
I would like to make a time-consuming call to the MATLAB engine, using engEvalString, but cannot figure out how to make the call asynchronous. No callback is necessary (but would be nice if possible).
The following is a minimum example of what doesn't work.
#include <boost/thread.hpp>
extern "C" {
#include <engine.h>
}
int main()
{
Engine* eng = engOpen("");
engEvalString(eng,"x=10");
boost::thread asyncEval(&engEvalString,eng,"y=5");
boost::this_thread::sleep(boost::posix_time::seconds(10));
return 0;
}
After running this program, I switch to the MATLAB engine window and find:
» x
x =
10
» y
Undefined function or variable 'y'.
So it seems that the second call, which should set y=5, is never processed by the MATLAB engine.
The thread definitely runs, you can check this by moving the engEvalString call into a local function and launching this as the thread instead.
I'm really stumped here, and would appreciate any suggestions!
EDIT: As Shafik pointed out in his answer, the engine is not thread-safe. I don't think this should be an issue for my use case, as the calls I need to make are ~5 seconds apart, for a calculation that takes 2 seconds. The reason I cannot wait for this calculation, is that the C++ application is a "medium-hard"-real-time robot controller which should send commands at 50Hz. If this rate drops below 30Hz, the robot will assume network issues and close the connection.
So, I figured out the problem, but would love it if someone could explain why!
The following works:
#include <boost/thread.hpp>
extern "C" {
#include <engine.h>
}
void asyncEvalString()
{
Engine* eng = engOpen("");
engEvalString(eng,"y=5");
}
int main()
{
Engine* eng = engOpen("");
engEvalString(eng,"x=10");
boost::thread asyncEvalString(&asyncEvalString);
boost::this_thread::sleep(boost::posix_time::seconds(1));
engEvalString(eng,"z=15");
return 0;
}
As you can see, you need to get a new pointer to the engine in the new thread. The pointer returned in asyncEvalString is different to the original pointer returned by engOpen in the main function, however both pointers continue to operate without problem:
» x
x =
10
» y
y =
5
» z
z =
15
Finally, to tackle the problem of thread safety, a mutex could be set up around the engEvalString calls to ensure only one thread uses the engine at any one time. The asyncEvalString function could also be modified to trigger a callback function once the engEvalString function has been completed.
I would however appreciate someone explaining why the above solution works. Threads share heap allocated memory of the process, and can access memory on other threads' stacks (?), so I fail to understand why the first Engine* was suddenly invalid when used in a separate thread.
So according to this Mathworks document it is not thread safe so I doubt this will work:
http://www.mathworks.com/help/matlab/matlab_external/using-matlab-engine.html
and according to this document, engOpen forks a new process which would probably explain the rest of the behavior you are seeing:
http://www.mathworks.com/help/matlab/apiref/engopen.html
Also see, threads and forks, think twice about mixing them:
http://www.linuxprogrammingblog.com/threads-and-fork-think-twice-before-using-them

c++ threads - parallel processing

I was wondering how to execute two processes in a dual-core processor in c++.
I know threads (or multi-threading) is not a built-in feature of c++.
There is threading support in Qt, but I did not understand anything from their reference. :(
So, does anyone know a simple way for a beginner to do it. Cross-platform support (like Qt) would be very helpful since I am on Linux.
Try the Multithreading in C++0x part 1: Starting Threads as a 101. If you compiler does not have C++0x support, then stay with Boost.Thread
Take a look at Boost.Thread. This is cross-platform and a very good library to use in your C++ applications.
What specifically would you like to know?
The POSIX thread (pthreads) library is probably your best bet if you just need a simple threading library, it has implementations both on Windows and Linux.
A guide can be found e.g. here. A Win32 implementation of pthreads can be downloaded here.
Edit: Didn't see you were on Linux. In that case I'm not 100% sure but I think the libraries are probably already bundled in with your GCC installation.
I'd recommend using the Boost libraries Boost.Thread instead. This will wrap platform specifics of Win32 and Posix, and give you a solid set of threading and synchronization objects. It's also in very heavy use, so finding help on any issues you encounter on SO and other sites is easy.
You can search for a free PDF book "C++-GUI-Programming-with-Qt-4-1st-ed.zip" and read Chapter 18 about Multi-threading in Qt.
Concurrent programming features supported by Qt includes (not limited to) the following:
Mutex
Read Write Lock
Semaphore
Wait Condition
Thread Specific Storage
However, be aware of the following trade-offs with Qt:
Performance penalties vs native threading libraries. POSIX thread (pthreads) has been native to Linux since kernel 2.4 and may not substitute for < process.h > in W32API in all situations.
Inter-thread communication in Qt is implemented with SIGNAL and SLOT constructs. These are NOT part of the C++ language and are implemented as macros which requires proprietary code generators provided by Qt to be fully compiled.
If you can live with the above limitations, just follow these recipes for using QThread:
#include < QtCore >
Derive your own class from QThread. You must implement a public function run() that returns void to contain instructions to be executed.
Instantiate your own class and call start() to kick off a new thread.
Sameple Code:
#include <QtCore>
class MyThread : public QThread {
public:
void run() {
// do something
}
};
int main(int argc, char** argv) {
MyThread t1, t2;
t1.start(); // default implementation from QThread::start() is fine
t2.start(); // another thread
t1.wait(); // wait for thread to finish
t2.wait();
return 0;
}
As an important note in c++14, the use of concurrent threading is available:
#include<thread>
class Example
{
auto DoStuff() -> std::string
{
return "Doing Stuff";
}
auto DoStuff2() -> std::string
{
return "Doing Stuff 2";
}
};
int main()
{
Example EO;
std::string(Example::*func_pointer)();
func_pointer = &Example::DoStuff;
std::future<string> thread_one = std::async(std::launch::async, func_pointer, &EO); //Launching upon declaring
std::string(Example::*func_pointer_2)();
func_pointer_2 = &Example::DoStuff2;
std::future<string> thread_two = std::async(std::launch::deferred, func_pointer_2, &EO);
thread_two.get(); //Launching upon calling
}
Both std::async (std::launch::async, std::launch::deferred) and std::thread are fully compatible with Qt, and in some cases may be better at working in different OS environments.
For parallel processing, see this.