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.
Related
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
Im making a MIDI generator in C++ using JUCE framework.
I'd like to do the generating in a different thread so it won't block my entire program.
This is how I make my thread:
std::thread generationThread (&MainContentComponent::generateProgression,var1, var2);
generateProgression is the function that generate's MIDI based on var1 (integer) and var2 (boolean)
The thread is created in the MainContentComponent class, and generateProgression is a function of that class.
The problem is that I'm getting a compile error saying : "Attempt to use a deleted function".
Could anyone tell me what I'm doing wrong?
Not sure why I got so many downvotes on this one.
Luckily a friend of mine told me what was wrong.
I needed to also give the current context.
As the thread is created in the class that also contains the function the context can just be "this".
std::thread(&Fooclass::fooMainloopMemberFunction, context, argument);
or in my case
std::thread generationThread (&MainContentComponent::generateProgression,this,var1, var2);
I am working on very large c++ project, it has lot of real time critical functions and also lot of slow background functions. These background functions should not be called from time critical functions. So is there way to detect these background functions being called from critical functions? compile time would be good but anyway I like to detect before these background functions.
More info, both slow and critical functions are part of same class and share same header.
Some more information, Critical functions runs under really faster thread (>=10KHz) slower one runs under different slower thread (<=1KHz). Class member variables are protected using critical sections in slow functions since both use same class member variables. That's reason calling slow functions in critical functions will slowdown overall system performance. That's reason I like to find all these kind of functions automatically instead of manual checking.
Thanks....
You need to leverage the linker. Separate the "realtime" and slow functions into two modules, and link them in the correct order.
For example, split the files into two directories. Create a lib from each directory (ranlib the object files together) then link your final application using:
c++ -o myapp main.o lib1/slowfns.a lib2/realtime.a
If you try to call anything from slowfns.a in realtime.a, depending on the compiler, it will fail to link (some compilers may need options to enforce this).
In addition, this lets you easily manage compile-time declarations too: make sure that the headers from the slowfns library aren't on the include path when compiling the "realtime" funcitons library for added protection.
Getting a compile-time detection other than the one proposed by Nicholas Wilson will be extremely hard if not impossible, but assuming "background" really refers to the functions, and not to multiple threads (I saw no mention of threads in the question, so I assume it's just an odd wording) you could trivially use a global flag and a locker object, and either assert or throw an exception. Or, output a debug message. This will, of course, be runtime-only -- but you should be able to very quickly isolate the offenders. It will also be very low overhead for debug builds (almost guaranteed to run from L1 cache), and none for release builds.
Using CaptureStackBackTrace, one should be able to capture the offending function's address, which a tool like addr2line (or whatever the MS equivalent is) can directly translate to a line in your code. There is probably even a toolhelp function that can directly do this translation (though I wouldn't know).
So, something like this (untested!) might do the trick:
namespace global { int slow_flag = 0; }
struct slow_func_locker
{
slow_func_locker() { ++global::slow_flag; }
~slow_func_locker(){ --global::slow_flag; }
};
#indef NDEBUG
#define REALTIME if(global::slow_flag) \
{ \
void* backtrace; \
CaptureStackBackTrace(0, 1, &backtrace, 0); \
printf("RT function %s called from %08x\n", __FUNCTION__, backtrace); \
}
#define SLOW_FUNC slow_func_locker slow_func_locker_;
#else
#define REALTIME
#define SLOW_FUNC
#endif
foo_class::some_realtime_function(...)
{
REALTIME;
//...
};
foo_class::some_slow_function(...)
{
SLOW_FUNC;
//...
some_realtime_function(blah); // this will trigger
};
The only real downside (apart from not being compile-time) is you have to mark each and every slow and realtime function with either marker, but since the compiler cannot magically know which is what, there's not much of a choice anyway.
Note that the global "flag" is really a counter, not a flag. The reason for this is that a slow function could immediately call another slow function that returns and clears the flag -- incorrectly assuming a fast function now (the approach with critical sections suggested by xgbi might deadlock in this case!). A counter prevents this from happening. In presence of threads, one might replace int with std::atomic_int, too.
EDIT:
As it is clear now that there are really 2 threads running, and it only matters that one of them (the "fast" thread) does not ever call a "slow" function, there is another simple, working solution (example using Win32 API, but could be done with POSIX either way):
When the "fast" thread starts up (the "slow" thread does not need to do this), store the thread ID somewhere, either as global variable, or as member of the object that contains all the fast/slow functions -- anywhere where it's accessible:
global::fast_thread_id = GetCurrentThreadId();
The macro to bail out on "unwelcome" function calls could then look like:
#define CHECK_FAST_THREAD assert(GetCurrentThreadID() != global::fast_thread_id)
This macro is then added to any "slow" function that should never be called from the "fast" thread. If the fast thread calls a function that it must not call, the assert triggers and it is known which function is called.
Don't know how to do that at compile time, but for runtime, maybe use a mutex?
static Mutex critical_mutex;
#define CALL_SLOW( f ) if( critical_mutex.try_lock() == FAIL) \
printf("SLOW FUNCTION " #f" called while in CRITICAL\n");\
f
#define ENTER_CRITICAL() critical_mutex.lock()
#define EXIT_CRITICAL() critical_mutex.unlock()
Whenever you use a slow function while in a critical section, the trylock will fail.
void slow_func(){
}
ENTER_CRITICAL();
CALL_SLOW( slow_func() );
EXIT_CRITICAL();
Will print:
SLOW FUNCTION slow_func() called while in CRITICAL
If you need speed, you can implement your lightweight mutex with interlockedincrement on windows or __sync* functions on linux.
Preshing has an awesome set of blog posts about this HERE.
If you're free to modify the code as you wish, there's a type-system-level solution that involves adding some boilerplate.
Basically, you create a new class, SlowFunctionToken. Every slow function in your program takes a reference to SlowFunctionToken. Next, you make SlowFunctionToken's default and copy constructors private.
Now only functions that already have a SlowFunctionToken can call slow functions. How do you get a SlowFunctionToken? Add friend declarations to SlowFunctionToken; specifically, friend the thread entry functions of the threads that are allowed to use slow functions. Then, create local SlowFunctionToken objects there and pass them down.
class SlowFunctionToken;
class Stuff {
public:
void FastThread();
void SlowThread();
void ASlowFunction(SlowFunctionToken& sft);
void AnotherSlowFunction(SlowFunctionToken& sft);
void AFastFunction();
};
class SlowFunctionToken {
SlowFunctionToken() {}
SlowFunctionToken(const SlowFunctionToken&) {}
friend void Stuff::SlowThread();
};
void Stuff::FastThread() {
AFastFunction();
//SlowFunctionToken sft; doesn't compile
//ASlowFunction(???); doesn't compile
}
void Stuff::SlowThread() {
SlowFunctionToken sft;
ASlowFunction(sft);
}
void Stuff::ASlowFunction(SlowFunctionToken& sft) {
AnotherSlowFunction(sft);
AFastFunction(); // works, but that function can't call slow functions
}
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.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Does the program execution always start from main in C?
i want to start the execution of my program which contains 2 functions (excluding main)
void check(void)
void execute(void)
i want to start my execution from check(), is it possible in c/c++?
You can do this with a simple wrapper:
int main()
{
check();
}
You can't portably do it in any other way since the standard explicitly specifies main as the program entry point.
EDIT for comment: Don't ever do this. In C++ you could abuse static initialization to have check called before main during static init, but you still can't call main legally from check. You can just have check run first. As noted in a comment this doesn't work in C because it requires constant initializers.
// At file scope.
bool abuse_the_language = (check(), true);
int main()
{
// No op if desired.
}
Various linkers have various options to specify the entry point. Eg. Microsoft linker uses /ENTRY:function:
The /ENTRY option specifies an entry point function as the starting
address for an .exe file or DLL.
GNU's ld uses the -e or ENTRY() in the command file.
Needles to say, modifying the entry point is a very advanced feature which you must absolutely understand how it works. For one, it may cause skipping the loading the standard libraries initialization.
int main()
{
check();
return 0;
}
Calling check from main seems like the most logical solution, but you could still explore using /ENTRY to define another entry point for your application. See here for more info.
You cannot start in something other than main, although there are ways to have some code execute before main.
Putting code in a static initialization block will have the code run prior to main; however, it won't be 100% controllable. while you can be assured it runs prior to main, you cannot specify the order that two static initialization blocks will run prior to them both executing before main.
Linkers and loaders both have the concept of main held as a shared "understood" start of a C / C++ program; however, there is code that runs prior to main. This code is responsible for "setting up the environment" of the program (things like setting up stdin or cin). By putting code in a static initialization block, you effectively say, "hey you need to do this too to have the right environment". Generally, this should be something small, that can stand independently in execution order of other items.
If you need two or three things to execute in order before main, then make them into proper functions and call them at the beginning of main.
There is a contrived way to achieve that, but it is nothing more than a hack.
The idea is to create a static library containing the main function, and make it call your "check" function.
The linker will resolve the symbol when linking against your "program", and your "program" code will indeed not have a main by itself.
This is NOT recommended, unless you have very specific needs (an example that pops to mind is Windows Screensavers, as the helper library that comes with the Windows SDK has a main function that performs specific initialization like parsing the command line).
It may be supportted by the compiler. For example, gcc, you can use -nostartfiles and --entry=xxx to set the entry point of the program. The default entry point is _start, which will call the function main.
You can "intercept" the call to main by creating an object before the main starts. The constructor needs to execute your function.
#include <iostream>
void foo()
{
// do stuff
std::cout<<"exiting from foo" <<std::endl;
}
struct A
{
A(){ foo(); };
};
static A a;
int main()
{
// something
std::cout<<"starting main()" <<std::endl;
}
I have found solution to my own question.
we can simply use
#pragma startup function-name <priority>
#pragma exit function-name <priority>
These two pragmas allow the program to specify function(s) that should be called either upon program startup (before the main function is called), or program exit (just before the program terminates through _exit).
The specified function-name must be a previously declared function taking no arguments and returning void; in other words, it should be declared as:
void func(void);
The optional priority parameter should be an integer in the range 64 to 255. The highest priority is 0. Functions with higher priorities are called first at startup and last at exit. If you don't specify a priority, it defaults to 100.
thanks!