C++ Threading : Attempt to use a deleted function - c++

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);

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

C++ Curious case of passing typename/datatype name/class name to thread constructor

I have returned to c++ after long years of Java/Node.js programming so, I am out of touch with the templates (I am working on that).
While revising concurrency, I accidentally stumbled upon the following case
class Test
{
};
int main()
{
std::thread t(Test);
}
What I was experimenting with was, what if I pass a non-callable object and then I would study the error and source code. But I accidentally passed the type name. The program compiled an ran with no issue and I was baffled.
Then I tried something more stupid
int main()
{
std::thread t1(int);
}
And somehow it worked as well.
Though these two cases compiled and ran properly. I don't get how.
If it tried t.join() or t1.join() I get following compilation error
t.join() cannot be resolved
I just simply just don't get what is happening in these two cases and how t.join() could not be resolved.
My research on it so far
I spend a significant amount of time trying to figure out how the compiler would have figured out whether the given value is callable. I came across this link: find out if a C++ object is callable
It made a lot of sense because of member detection idiom but when I checked the source of gcc it seemed it used std::_Bind_simple of functional header/library to figure this out. But it didn't solve my query.
Then, this post how std::thread constructor detects rvalue reference? asked the similar question but the answer made no sense to me.
Any sort of assistance will be very appreciated
Thanks to #Jaroda42 what I was doing was making a function declaration in local scope.
std::thread t(Test);
Where function being being t return type be std::thread and parameters being class type Test.
It was really stupid but this is what one get if one leaves a language for long time.

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.

Generate a List/Set by preprocessor/template from different modules and has to be filled before linking

I have some global variables (classes) that as I understand have created before main() call. I need some technique to add data to a List of something either global or as member of that class from any part of my code and it have to be filled before Linker. To use it inside globally created classes. Is it possible? I did not find any similar solution or even question, so any help will be appreciated.
Detailed example:
I've have singleton class which has a variable that was filled in the constructor. All other classes use data from the class at run time someone early someone later. Singleton class is created at the begin of main function. I am using singleton in different projects, data that it has mostly universal for all projects and modules except special flag which should show requirement for this module. If singleton throw exception program exits and we know it at the first steps of execution because singleton creates at first lines of the main. So singleton has a lot of universal data for all projects but I need to add flags to point for singleton which data is required for each module. I have created template for main so for each project I have the same main with just simple define PROJECT_NAME later I add .cpp to the project and they have to register which data is required and which not.
This explanation not looks like perfect, if it is not understandable don't hesitate to say it I will organize it more deliberately.
Edited:
I'm still looking for solution in the Internet, and found constexpr it looks like what I need, but at this moment it is not supported by all compilers, is there some workaround ?
First step is to not use global variables, but instead use static variables within a global function. The first time the function is called the variable will be initialized and then have the function return a reference to the varaible.
my_class& instnace() {
static my_class i;
return i;
}
A list example:
std::list<my_class>& global_list() {
static std::list<my_class> m; return m;
}
static int x = []()->int{ global_list().push_back(my_class); return 0;}();
If you want to accomplish what you want from different modules , one of the way is to have things done is some sort of callback function when your dll is loaded.
One windows it is DLLMain.
An optional entry point into a dynamic-link library (DLL). When the
system starts or terminates a process or thread, it calls the
entry-point function for each loaded DLL using the first thread of the
process. The system also calls the entry-point function for a DLL when
it is loaded or unloaded using the LoadLibrary and FreeLibrary
functions.
On other platforms with gcc you can get by the [attribute constructor]
constructor The constructor attribute causes the function to be called
automatically before execution enters main (). Similarly, the
destructor attribute causes the function to be called automatically
after main () has completed or exit () has been called. Functions with
these attributes are useful for initializing data that will be used
implicitly during the execution of the program. These attributes are
not currently implemented for Objective-C.
Warning
It is very easy to shoot yourself in the foot with this method. At least on windows that are lot of things you cannot do in the dll entry point. Please read your compiler/os documentation to see what the limitations are.

How to wrap multithreaded C++ library using Python C/API?

This is a somewhat long question, but I hope I can express it clearly.
I am trying to wrap a C++ library using Python/C API. The main library, say, mylib, has its own object system (it is something like an interpreter for another language ) and uniquely identifies each object in its environment by an Id. It creates multiple threads in its init() function and does different things on different threads (say creating objects on one thread and interpreting commands in another thread).
Now I am trying to wrap it in two levels:
I created a Dummy class with the Id of an object in mylib. The Dummy constructor actually calls a function in mylib to create a new object and store its Id. Other methods in Dummy class similarly call equivalent functions in mylib. This does not use Python/C API.
I created mylibmodule.cpp, which uses the Python/C API to provide the functions that will be called from the Python interpreter.
I call the init() function of mylib in PyMODINIT_FUNC init_mylib().
I code functions like :
static PyObject * py_new_Dummy(PyObject* self, PyObject *args){
// ... process arguments
return reinterpret_cast<PyObject*>(new Dummy);
}
Note that the Dummy constructor does call functions in mylib that are executed on threads created by using pthreads.
I compile this into _mylib.so and I have a mylib.py:
import _mylib
class MyClass(obj):
def __init__(self, *args)
self.__ptr = _mylib.py_new_Dummy()
Now to the actual problem: I can import mylib in the Python interpreter, but as soon as I try:
a = MyClass(some_args)
I get a segmentation fault. A gdb backtrace shows
Program received signal SIGSEGV, Segmentation fault.
__pthread_mutex_lock (mutex=0x0) at pthread_mutex_lock.c:50
Even funnier is that if I disable spawning multiple threads in the mylib code (still linked with pthreads), I can create MyClass instances, but I get a segmentation violation at exit from the Python interpreter.
The "Thin Ice" section in the Python documentation (http://docs.python.org/extending/) did not enlighten me. I am wondering if I should use PyGILState_Ensure and PyGILState_Release around all Python C/API calls in mylibmodule.cpp. Or should it be Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS?
Can anybody help? Is there any definitive documentation on how exactly Python plays with pthreads?
From your description it doesn't really sound like a threading issue at all: you claim you define the Dummy class without using the Python API, but that would mean Dummy instances are not PyObjects, so the reinterpret_cast will do the wrong thing. You can't create PyObjects by just instantiating a C++ class; you need to play along with Python's object system and create a proper PyType struct and a PyObject struct and properly initialize both. You also need to make sure your refcounts are correct.
Once you have that sorted, the main thing to remember about threads is that any call that touches Python objects or that uses any of the Python API (except the functions to grab the GIL) must have the GIL acquired. If any of the threads in your C++ library try to call back to Python code or touch Python objects, the access needs to be wrapped in PyGILState_Ensure/PyGILState_Release.
Thank you Thomas for pointing out the red herring. The problem was in the initialization of the threads in the C++ side.
And yes, it did not need any GIL manipulation as the none of the additional C++ threads were accessing Python C/API.