error C2064: term does not evaluate to a function taking 0 arguments thread.hpp(60) - multithreading

I'm creating c++ game server. The server creates many objects monster, and every monster should have its thread with specific function.
I get error :
error C2064: term does not evaluate to a function taking 0 arguments
thread.hpp(60) : while compiling class template member function 'void
boost::detail::thread_data<F>::run(void)'
monster.cpp:
#include "monster.h"
monster::monster(string temp_mob_name)
{
//New login monster
mob_name = temp_mob_name;
x=rand() % 1000;
y=rand() % 1000;
boost::thread make_thread(&monster::mob_engine);
}
monster::~monster()
{
//Destructor
}
void monster::mob_engine()
{
while(true)
{
Sleep(100);
cout<< "Monster name"<<mob_name<<endl;
}
}
monster.h:
#ifndef _H_MONSTER_
#define _H_MONSTER_
//Additional include dependancies
#include <iostream>
#include <string>
#include "boost/thread.hpp"
using namespace std;
class monster
{
public:
//Functions
monster(string temp_mob_name);
~monster();
//Custom defined functions
void mob_engine();
int x;
int y;
};
//Include protection
#endif

mob_engine is a non-static member function, so it has an implicit this argument.
Try this:
boost::thread make_thread(boost::bind(&monster::mob_engine, this));
According to this similar question boost:thread - compiler error you can even avoid using bind by simply writing:
boost::thread make_thread(&monster::mob_engine, this);
Also, you will probably want to declare a boost::thread member variable to keep a reference to the thread.

Related

c++ error in my thread constructor passing the function

I'm trying to make a thread every time a call a function from a class, but i can't pass the function correctly:
file.h
#include <thread>
class Class
{
public:
Class(int a);
void ThreadBase(void (*func));
int CreateThread(void (*func));
};
file.cpp
#include <thread>
Class::Class(int a)
{
/**
* ...
*/
}
void Class:ThreadBase(void (*func))
{
while(1)
{
/**
* ...
*/
}
}
int Class:CreateThread(void (*func))
{
std::thread th(Class::ThreadBase, func);
}
Error:
error: reference to non-static member function must be called
CreateThread should call std::thread with a function and arguments for the function.
The problem is here:
std::thread th(Class::ThreadBase, func);
Class::ThreadBase is not a static function; so it can't be called directly. In this case; CreateThread should call the member function "ThreadBase" of 'this.'

Couldn't template<typename> deduce pointer type?

I have the following program, compile+run, no problem
#include <thread>
#include <future>
#include <iostream>
#include <algorithm>
void f(int* first,
int* last,
std::promise<int> accumulate_promise)
{
int sum = std::accumulate(first, last, 0);
accumulate_promise.set_value(sum); // Notify future
}
int main()
{
int numbers[] = { 1, 2, 3, 4, 5, 6 };
std::promise<int> accumulate_promise;
std::future<int> accumulate_future = accumulate_promise.get_future();
std::thread work_thread(f, begin(numbers), end(numbers),
std::move(accumulate_promise));
accumulate_future.wait(); // wait for result
std::cout << "result=" << accumulate_future.get() << '\n';
work_thread.join(); // wait for thread completion
}
But if I change "f" into a template:
template<typename Iterator>
void f(Iterator first,
Iterator last,
std::promise<int> accumulate_promise)
{
int sum = std::accumulate(first, last, 0);
accumulate_promise.set_value(sum); // Notify future
}
Then it fails compilation,gcc report that thread::thread() ctor cannot find proper overload:
error: no matching function for call to 'std::thread::thread(, int*, int*, std::remove_reference&>::type)'
What is the message indicating, anything wrong with my template?
How to fix it?
Thanks.
f is a template.
std::thread work_thread(f, begin(numbers), end(numbers),
std::move(accumulate_promise));
To put it in loose terms, std::thread's first parameter is either a function pointer or something that acts like a function pointer. It doesn't take a template as the first parameter.
A template becomes a class, or a function, when it is instantiated. The template gets instantiated when it gets used. So, given this template definition, and using it in a manner like this:
f(something.begin(), something.end(), some_kind_of_a_promise);
this instantiates a template, and uses it. To instantiate a template explicitly, without using it:
f<int *>
Now, you have an instantiated template here. The following works here:
std::thread work_thread(f<int *>, std::begin(numbers),
std::end(numbers),
std::move(accumulate_promise));
Tested with gcc 5.3.1

Issue in predicate function in wait in thread C++

I am trying to put the condition inside a function but it is throwing confusing compile time error . While if I write it in lambda function like this []{ retur i == k;} it is showing k is unidentified . Can anybody tell How to solve this problem .
#include <iostream>
#include <mutex>
#include <sstream>
#include <thread>
#include <chrono>
#include <condition_variable>
using namespace std;
condition_variable cv;
mutex m;
int i;
bool check_func(int i,int k)
{
return i == k;
}
void print(int k)
{
unique_lock<mutex> lk(m);
cv.wait(lk,check_func(i,k)); // Line 33
cout<<"Thread no. "<<this_thread::get_id()<<" parameter "<<k<<"\n";
i++;
return;
}
int main()
{
thread threads[10];
for(int i = 0; i < 10; i++)
threads[i] = thread(print,i);
for(auto &t : threads)
t.join();
return 0;
}
Compiler Error:
In file included from 6:0:
/usr/include/c++/4.9/condition_variable: In instantiation of 'void std::condition_variable::wait(std::unique_lock<std::mutex>&, _Predicate) [with _Predicate = bool]':
33:30: required from here
/usr/include/c++/4.9/condition_variable:97:14: error: '__p' cannot be used as a function
while (!__p())
^
wait() takes a predicate, which is a callable unary function returning bool. wait() uses that predicate like so:
while (!pred()) {
wait(lock);
}
check_func(i,k) is a bool. It's not callable and it's a constant - which defeats the purpose. You're waiting on something that can change. You need to wrap it in something that can be repeatedly callable - like a lambda:
cv.wait(lk, [&]{ return check_func(i,k); });

C++11 threads no matching function call

I am trying to make a threaded grabber for my OpenCV application. I am unable to figure out why this code doesn't compile. It gives me an error that I believe means that the function call is wrong. However, it is the exact same way how I start a thread using std::thread usually! I want to use std::thread to accomplish it because it will offer more platform-independent compatibility, so please don't tell me to use a platform-specific library. I also want this to be STL-based, so no Boost or DLib. In my main.cpp, I have a working thread application, the code below:
#include <iostream>
#include <fstream>
#include <string>
#include <thread>
#include <mutex>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/objdetect/objdetect.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#define read_failure_threshold 512
long grabbers_active = 0;
namespace dev
{
class grabber
{
private:
bool enabled = false;
std::mutex lock;
int capture_mode;
int capture_id;
unsigned long read_failures = 0;
std::string stream;
std::string grabber_name;
cv::Mat image;
public:
void grabber_t()
{
.......[unimportant code]........
}
grabber(std::string name, int captureMode, int captureId, std::string location)
{
.......[unimportant code]........
}
void start()
{
if(!enabled)
{
std::thread grabber_thread(grabber_t);
grabber_thread.detach();
}
enabled = true;
grabbers_active++;
}
cv::Mat getImage()
{
.......[unimportant code]........
}
};
}
[ERRORS:]
In file included from /media/storage/programming/yash101/repos/Other/STL+OpenCV/threaded_grabber_template/main.cpp:1:0:
/media/storage/programming/yash101/repos/Other/STL+OpenCV/threaded_grabber_template/template.hpp: In member function ‘void dev::grabber::start()’:
/media/storage/programming/yash101/repos/Other/STL+OpenCV/threaded_grabber_template/template.hpp:119:52: error: no matching function for call to ‘std::thread::thread(<unresolved overloaded function type>)’
std::thread grabber_thread(grabber_t);
^
/media/storage/programming/yash101/repos/Other/STL+OpenCV/threaded_grabber_template/template.hpp:119:52: note: candidates are:
In file included from /media/storage/programming/yash101/repos/Other/STL+OpenCV/threaded_grabber_template/template.hpp:4:0,
from /media/storage/programming/yash101/repos/Other/STL+OpenCV/threaded_grabber_template/main.cpp:1:
/usr/include/c++/4.8/thread:133:7: note: std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (dev::grabber::*)(); _Args = {}]
thread(_Callable&& __f, _Args&&... __args)
^
/usr/include/c++/4.8/thread:133:7: note: no known conversion for argument 1 from ‘<unresolved overloaded function type>’ to ‘void (dev::grabber::*&&)()’
/usr/include/c++/4.8/thread:128:5: note: std::thread::thread(std::thread&&)
thread(thread&& __t) noexcept
^
/usr/include/c++/4.8/thread:128:5: note: no known conversion for argument 1 from ‘<unresolved overloaded function type>’ to ‘std::thread&&’
/usr/include/c++/4.8/thread:122:5: note: std::thread::thread()
thread() noexcept = default;
^
/usr/include/c++/4.8/thread:122:5: note: candidate expects 0 arguments, 1 provided
make[2]: *** [CMakeFiles/build.dir/main.cpp.o] Error 1
make[1]: *** [CMakeFiles/build.dir/all] Error 2
make: *** [all] Error 2
The error log is also at the end of the code. The only errors I am worried about are the threading ones. The other ones are simple fixes, but require me to have the threading working.
I am in Ubuntu, using g++ (Ubuntu 4.8.2-19ubuntu1) 4.8.2. I have C++0x enabled in my CMakeLists.txt. Everything works perfectly in there
My main objective is to figure out why I am getting this error. I have been googling and trying different tricks for many hours, but nothing is working!
Thanks in advanced for your help :)
Change that :
std::thread grabber_thread(grabber_t);
Into that :
std::thread grabber_thread(&grabber::grabber_t, this);
grabber_t is a reference to non-static member function, you need to pass its address, but &grabber_t can't work as you must explicitly qualify name of member function when taking its address, thus resulting in &grabber::grabber_t.

boost:thread - compiler error

I wanted to use boost::thread in my program, but get the following compiler error (Visual Studio 2005):
Error 1 **error C2064**: term does not evaluate to a function taking 0
arguments d:\...\boost_1_37_0\boost\thread\detail\thread.hpp 56
Therefore I tried to recreate the problem in a small program and modified the working Hello World example from this site.
My test code now looks like this. Why is it not working inside a class?:
#include <boost/thread.hpp>
#include <iostream>
class HelloWorld
{
public:
void hello();
void entry();
};
void HelloWorld::entry()
{
boost::thread thrd(&HelloWorld::hello);
thrd.join();
}
void HelloWorld::hello()
{
std::cout << "Hello world, I'm a thread!" << std::endl;
}
int main(int argc, char* argv[])
{
HelloWorld *bla = new HelloWorld;
bla->entry();
return 0;
}
Try it like this - the boost::thread constructor is expecting a boost::function0 (which a function pointer is, but a member function pointer isn't, due to the this pointer).
void HelloWorld::entry()
{
boost::thread thrd(boost::bind(&HelloWorld::hello,this));
thrd.join();
}
Member functions have a this pointer as the first argument. Since there is a boost::thread constructor that accepts function arguments, you don't need to use boost::bind. This will also work:
void HelloWorld::entry()
{
boost::thread thrd(&HelloWorld::hello,this);
thrd.join();
}
If your function requires arguments, you can put them after the this pointer argument.
You are passing a member function to the thread object as the function to call when the thread starts. Since the thread doesn't have the object itself, it can't call the member function. You could make the hello function static, or look at the boost::bind library to send in the object.

Resources