No matching overloaded function found - Threads - c++

For the code snippet below, I keep getting the invoke error C6272. I have tried multiple things - passing using ref, without it and even testing as a simple thread. For context, the member function is a function that multiplies two sparse matrices and adds them to a linked list. Without using threads, the function works fine but threads returns an error.
mutex m;
vector<thread> a;
for (int q = 0; q < rhs.num_columns_; q++) {
a.push_back(thread(&SparseMatrix::mul_node, rhs_rows, lhs_rows, q, ref(newMatrix), ref(m)));
}
for (thread& t : a) {
t.join();
}
Declaration of the mul_node function
void SparseMatrix::mul_node(vector<vector<int>> rhs, vector<vector<int>> lhs, int pos_rhs, row_node* &newMatrix, mutex &m) const`
I have not been able to find a solution yet for the problem above, please let me know what exactly is causing the issue and how I can fix it? Thank you

Since the member function is not static you need to pass a pointer to the instance of the SparseMatrix on to the std::thread constructor too.
Simplified example:
#include <iostream>
#include <thread>
struct foo {
~foo() {
if(th.joinable()) th.join();
}
void run() {
th = std::thread(&foo::thread_func, this, 10, 20);
// ^^^^
}
void thread_func(int a, int b) {
std::cout << "doing the stuff " << a << ' ' << b << '\n';
}
std::thread th;
};
int main() {
foo f;
f.run();
}
Here 10 and 20 are passed as parameters to this->thread_func.

Related

C++ future async not working inside class [duplicate]

How can I operate std::async call on a member function?
Example:
class Person{
public:
void sum(int i){
cout << i << endl;
}
};
int main(int argc, char **argv) {
Person person;
async(&Person::sum,&person,4);
}
I want to call to sum async.
Person p;
call async to p.sum(xxx)
I didnt figure out if i can do it with std::async.
Dont want to use boost.
Looking for a one line async call way.
Something like this:
auto f = std::async(&Person::sum, &p, xxx);
or
auto f = std::async(std::launch::async, &Person::sum, &p, xxx);
where p is a Person instance and xxx is an int.
This simple demo works with GCC 4.6.3:
#include <future>
#include <iostream>
struct Foo
{
Foo() : data(0) {}
void sum(int i) { data +=i;}
int data;
};
int main()
{
Foo foo;
auto f = std::async(&Foo::sum, &foo, 42);
f.get();
std::cout << foo.data << "\n";
}
There are several ways, but I find it's most clear to use a lambda, like this:
int i=42;
Person p;
auto theasync=std::async([&p,i]{ return p.sum(i);});
This creates a std::future. For a complete example of this, I have a full example including a async-capable setup of mingw here:
http://scrupulousabstractions.tumblr.com/post/36441490955/eclipse-mingw-builds
You need to make sure that p is thread safe and that the &p reference is valid until the async is joined. (You can also hold p with a shared pointer, or in c++14, a unique_ptr or even move p into the lambda.)

How to start a variable number of threads in C++?

I am searching for a way to start multiple threads whose exact number can only be determined at runtime. The threads are not dependent on each other, so it's a fire-and-forget kind of problem.
The threads do need some context which is stored as internal variables of a class (Foo). Some of these variables are references. The class also holds a method that should be executed as the thread function (bar).
#include <iostream>
#include <string>
#include <vector>
#include <thread>
class Foo
{
public:
Foo(int a){
std::cout << "Created" << std::endl;
m_a = new int(a);
}
~Foo(){
std::cout << "Destroyed" << std::endl;
delete m_a;
}
void bar() {
std::cout << "Internal var: " << *m_a << std::endl;
}
private:
int* m_a;
};
int main() {
for(int i = 0; i < 5; i++) {
std::thread t(&Foo::bar, std::ref(Foo(i)));
// the threads will be joined at a later point, this is for demo purposes
}
return 0;
}
I get a compile error at this point:
error: use of deleted function ‘void std::ref(const _Tp&&) [with _Tp = Foo]’
I get it that this error is caused because of the temporary nature of the object created in the for-loop. But if I remove the std::ref function, I get a segfault: double free or corruption (fasttop)
I am sure that there must be a way of doing this, but I am unaware of that. I would expect some output like (probably in this order, but not guaranteed):
Created
Internal var: 0
Destroyed
Created
Internal var: 1
Destroyed
...
Thanks!
Problem 1: Foo is missing a copy/move constructor. See The rule of three/five/zero.
Add a copy constructor:
Foo(Foo const& that) : m_a(new int(*that.m_a)) {}
And/or a move constructor:
Foo(Foo && that) : m_a(that.m_a) { that.m_a = nullptr; }
Problem 2: Foo(i) is a temporary instance of Foo, it lives until the end of the full-expression (the ;).
std::thread t(&Foo::bar, std::ref(Foo(i)));
// ^
// Foo(i) is dead at this point while the thread is starting!
You want it to live longer than that, in order to be usable inside the thread.
For example, like this (also answers your question about creating threads in a loop):
int main() {
std::vector<Foo> inputs;
std::vector<std::thread> threads;
for(int i = 0; i < 5; i++) {
inputs.emplace_back(i);
threads.emplace_back(&Foo::bar, &inputs.back());
}
for (auto& t : threads) {
t.join();
}
}
Note: std::ref(Foo(i)) doesn't compile because it has protection against returning references to temporaries (precisely to prevent issues like these).
Here is a minimaly fixed version of your code:
it includes the move ctor for Foo class (and explicitely deletes copy ctor)
it moves the threads into a vector
it joins the threads
Code:
#include <string>
#include <vector>
#include <thread>
#include <iostream>
class Foo
{
public:
Foo(int a) {
std::cout << "Created" << std::endl;
m_a = new int(a);
}
~Foo() {
if (m_a != NULL) {
std::cout << "Destroyed" << std::endl;
delete m_a;
}
}
Foo(const Foo& other) = delete; //not used here
Foo(Foo&& other) {
std::cout << "Move ctor" << '\n';
m_a = other.m_a;
other.m_a = nullptr;
}
void bar() {
std::cout << "Internal var: " << *m_a << std::endl;
}
private:
int* m_a;
};
int main() {
std::vector<std::thread> vec;
for (int i = 0; i < 5; i++) {
std::thread t(&Foo::bar, Foo(i));
vec.push_back(std::move(t));
}
for (auto& t : vec) {
t.join();
}
return 0;
}
The chief design failure seems that t is a variable inside the loop. That means it's destroyed at the end of each iteration - you never have 5 std::thread instances at the same time. Also, you fail to call join on those threads.
The std::ref apparently hides this problem and replaces it with another problem, but your original thread creation was correct: std::thread t(&Foo::bar, Foo(i)).
You probably want a std::list<std::thread>, and use std::list::emplace_back to create a variable amount. std::list<std::thread> allows you to remove threads in any order from the list.

Is it safe to pass lambda to function that is going out of scope (lambda executes after the method returns)?

I am learning C++ so maybe my question is dumb. I am creating a function that takes a lambda as a parameter. I just want to know if its safe to call it when the lambda function goes out of scope. With code is easier to explain what I mean:
struct SomeStruct
{
// store pointer to callback function
void (*callback)(bool);
int arg1;
int arg2;
};
void some_method(int arg1, int arg2, void (*on_complete_callback)(bool))
{
SomeStruct s;
s.callback = on_complete_callback;
s.arg1 = arg1;
s.arg2 = arg2;
// this helper class will copy the struct even though it is passed by reference
SomeHelperClass->SomeQueue.enqueue( &s );
// do work on a separate task/thread
SomeHelperClass->CreateThread([](){
// get copy of struct
SomeStruct s_copy;
SomeHelperClass->SomeQueue.dequeue( &s_copy );
// do work that takes time to complete
// IS IT SAFE TO CALL THIS CALLBACK FUNCTION?
s_copy.callback(true);
});
}
So my question is given that code if its safe to have something like this?
void method_1()
{
void (*foo)(bool) = [](bool completedCorrectly)
{
cout << "task completed :" << completedCorrectly << endl;
};
some_method(1,2,foo);
// at this point foo should be deleted no?
// why does this work if foo is executed after method_1 completes and its stack is deleted?
// can I have code like that?
}
Edit 2
Here is the same question with working code instead of pseudo code:
#include <iostream> //for using cout
using namespace std; //for using cout
// 3 pointers
int* _X; // points to integer
int* _Y; // points to integer
void (*_F)(int); // points to function
void print_values()
{
cout << "x=" << *_X << " and y=" << *_Y << endl;
}
void some_function()
{
// create variables that live on stack of some_function
int x = 1;
int y = 2;
void (*foo)(int) = [](int someInt)
{
cout << "value passed to lambda is:" << someInt << endl;
};
// point global variables to variables created on this stack x,y and foo
_X = &x;
_Y = &y;
_F = foo;
// works
_F(11);
// works
print_values();
// when exiting variables x,y and foo should be deleted
}
int main(void)
{
// call some function
some_function();
// DOES NOT WORK (makes sense)
print_values();
// WHY DOES THIS WORK? WHY FOO IS NOT DISTROYED LIKE X AND Y?
_F(10);
return 0;
}
If I where to call that method many times and each time with a different lambda will it work? Will the callback method call the correct lambda every time?
A lambda expression is like a class. It is a blueprint for instantiating objects. Classes exist only in source code. A program actually works with objects created from the blueprint defined by a class. Lambda expressions are a source code blueprint for creating closures. Each lambda expression is transformed into a class by the compiler and instantiated into an object called closure. This class has the ability to capture values (that's that the [] part does) and take parameters (that's that the () part does) for its call operator.
Here is an example:
int main()
{
int i = 42;
auto l = [i](int const x){std::cout << x+i << '\n';};
l(2);
}
The compiler transforms this into something similar to the following (generated with https://cppinsights.io/).
int main()
{
int i = 42;
class __lambda_6_11
{
public:
inline /*constexpr */ void operator()(const int x) const
{
std::operator<<(std::cout.operator<<(x + i), '\n');
}
private:
int i;
public:
__lambda_6_11(int & _i)
: i{_i}
{}
};
__lambda_6_11 l = __lambda_6_11{i};
l.operator()(2);
}
You can see here a class that implements the call operator (operator()) with an int argument. You can also see the constructor taking an argument of type int. And then you can see the instantiation of this class at the end of main and the invocation of its call operator.
I hope this helps you understand better how lambdas work.

Passing Class Method to std::async in C++ [duplicate]

How can I operate std::async call on a member function?
Example:
class Person{
public:
void sum(int i){
cout << i << endl;
}
};
int main(int argc, char **argv) {
Person person;
async(&Person::sum,&person,4);
}
I want to call to sum async.
Person p;
call async to p.sum(xxx)
I didnt figure out if i can do it with std::async.
Dont want to use boost.
Looking for a one line async call way.
Something like this:
auto f = std::async(&Person::sum, &p, xxx);
or
auto f = std::async(std::launch::async, &Person::sum, &p, xxx);
where p is a Person instance and xxx is an int.
This simple demo works with GCC 4.6.3:
#include <future>
#include <iostream>
struct Foo
{
Foo() : data(0) {}
void sum(int i) { data +=i;}
int data;
};
int main()
{
Foo foo;
auto f = std::async(&Foo::sum, &foo, 42);
f.get();
std::cout << foo.data << "\n";
}
There are several ways, but I find it's most clear to use a lambda, like this:
int i=42;
Person p;
auto theasync=std::async([&p,i]{ return p.sum(i);});
This creates a std::future. For a complete example of this, I have a full example including a async-capable setup of mingw here:
http://scrupulousabstractions.tumblr.com/post/36441490955/eclipse-mingw-builds
You need to make sure that p is thread safe and that the &p reference is valid until the async is joined. (You can also hold p with a shared pointer, or in c++14, a unique_ptr or even move p into the lambda.)

using function object though function pointer is required

I have to use some legacy code expecting a function pointer, let's say:
void LEGACY_CODE(int(*)(int))
{
//...
}
However the functionality I have is within a functor:
struct X
{
Y member;
X(Y y) : member(y)
{}
int operator()(int)
{
//...
}
};
How should I modify/wrap class X so that LEGACY_CODE can access the functionality within X::operator()(int) ?
Your question makes no sense. Whose operator do you want to call?
X a, b, c;
LEGACY_CODE(???); // what -- a(), b(), or c()?
So, in short, you cannot. The member function X::operator() is not a property of the class alone, but rather it is tied to an object instance of type X.
Search this site for "member function" and "callback" to get an idea of the spectrum of possible approaches for related problems.
The crudest, and quite possibly not-safe-for-use, workaround to providing a free function would go like this:
X * current_X; // ugh, a global
int dispatch(int n) { current_X->operator()(n); }
int main()
{
X a;
current_X = &a;
LEGACY_CODE(dispatch);
}
You can see where this is going...
A simple wrapper function looks like:
int wrapperfunction(int i) {
Functor f(params);
return f(i);
}
If you want to be able to pass the parameters to the functor itself, the simplest way is to sneak them in using (brr) a global variable:
Functor functorForWrapperfunction;
int wrapperfunction(int i) {
functorForWrapperfunction(i);
}
// ...
void clientCode() {
functorForWrapperfunction = Functor(a,b,c);
legacyCode(wrapperfunction);
}
You can wrap it with a class with a static method and a static member if you want.
Here's one compile-time solution. Depending on what you need, this might be a too limited solution for you.
template<typename Func, int Param>
int wrapper(int i)
{
static Func f(Param);
return f(i);
}
A thread-safe version under the restriction that the legacy code is not called with different parameters in a thread.
IMHO, one cannot get rid of global storage.
#include <boost/thread.hpp>
#include <boost/thread/tss.hpp>
class AA
{
public:
AA (int i) : i_(i) {}
void operator()(int j) const {
static boost::mutex m; // do not garble output
boost::mutex::scoped_lock lock(m);
std::cout << " got " << j << " on thread " << i_ << std::endl;
Sleep(200); }
int i_;
};
// LEGACY
void legacy_code(void (*f)(int), int i) { (*f)(i); }
// needs some global storage through
boost::thread_specific_ptr<AA> global_ptr;
void func_of_thread(int j)
{
AA *a = global_ptr.get();
a->operator()(j);
}
void worker(int i)
{
global_ptr.reset(new AA(i));
for (int j=0; j<10; j++)
legacy_code(func_of_thread,j);
}
int main()
{
boost::thread worker1(worker,1) , worker2(worker,2);
worker1.join(); worker2.join();
return 0;
}