C++11 std::thread giving error: no matching function to call std::thread::thread - c++

I'm testing c++11 threads with this code, but when creating the thread, I'm having the error no matching function for call to 'std::thread::thread()'.
It's like if there was something wrong with the function I'm giving to std::thread ctr, but I don't see how it's wrong. It is incompleted, but it looks right to me:
Header:
#ifndef CONNECTION_H
#define CONNECTION_H
#include <thread>
#include <mysql++.h>
class Connection
{
public:
Connection(std::string mysqlUser, std::string mysqlPassword);
~Connection();
private:
std::string mysqlUser;
std::string mysqlPassword;
std::string mysqlIP;
int mysqlPort;
mysqlpp::Connection mysqlConnection;
std::thread connectionThread;
void threadLoop();
};
#endif // CONNECTION_H
Source:
#include "connection.h"
Connection::Connection(std::string mysqlUser, std::string mysqlPassword)
{
this->mysqlUser = mysqlUser;
this->mysqlPassword = mysqlPassword;
this->mysqlIP = "localhost"; //default
this->mysqlPort = 3306; //default
//Launch thread
std::thread connectionThread(threadLoop);
}
Connection::~Connection(){
mysqlConnection.disconnect();
}
void Connection::threadLoop(){
//Connect to mySQL database
mysqlConnection = new mysqlpp::Connection(false);
if(mysqlConnection.connect(NULL, mysqlIP.c_str(), mysqlUser.c_str(), mysqlPassword.c_str(), mysqlPort)){
std::string consulta = "SELECT * FROM 'Coordinates'";
mysqlpp::Query query = mysqlConnection.query(consulta);
mysqlpp::StoreQueryResult res = query.store();
query.reset();
}
while(true){
// Stuff
}
}

The problem is that threadLoop is a member function, but there is no object for it to be applied to. Just guessing:
std::thread connectionThread(&Connection::threadLoop, this);
But that's just the syntactic issue; there's a logic problem, too: that line creates a local object of type std::thread that goes away when the function returns. Its destructor will call std::terminate() because the thread has not been joined. Most likely, this was supposed to attach a thread to the connectionThread member. To do that:
std::thread thr(threadLoop, this);
std::swap(thr, connectionThread);

Your code has two problems:
You are providing incomplete information to the std::thread constructor
You are destroying the std::thread before it is joined with the main thread.
For the first problem, as Pete Becker suggests, you need to provide the object on which the function will be called, because the constructor for std::thread has no other way to know it. Assuming that you want to call function threadLoop() on the Connection object you are constructing, you can do this:
//Launch thread
std::thread connectionThread(threadLoop, this);
Internally, the constructor will call this->threadLoop() (where this is the Connection* parameter it received, not the std::thread itself, of course). And you will be fine.
The second problem is that your std::thread is destroyed immediately after starting, without having joined it to the main thread: this will call terminate(), which is not a good thing. Once again, Pete suggests a good alternative. Replace the above code with this:
// Launch thread
std::thread thr(threadLoop, this);
std::swap(thr, connectionThread);
The situation before this code is as follows:
You have a trivial std::thread object, connectionThread, which does not really represent a thread
After executing the first line of code:
You still have connectionThread
You also have a live thread represented by the std::thread object thr, which will be destroyed at the end of the Connection constructor, causing a call to terminate() because it is never joined to the main thread.
Fortunately, the second line of code comes to the rescue. After executing it:
You have a trivial std::thread, thr, which can be safely destroyed because it does not represent a real thread (so it is not joinable)
You have a live thread represented by connectionThread, an object that will not be destroyed as long as the Connection object exists.
Now, the problem is that you want to join connectionThread to the main thread before it is destroyed, but you also want to avoid blocking the main thread. The right time to do this join is the latest possible time: when connectionThread is about to be destroyed. And this happens at the destructor of Connection. So we'll add a line to this destructor, this way:
Connection::~Connection(){
mysqlConnection.disconnect();
connectionThread.join(); // Now connectionThread can be safely destroyed
}
Besides, this is the safest place to call join(), because it ensures that you will never destroy an unjoined connectionThread. This is RAII in action; if you are not familiar with the concept of RAII (or RIIA, as it is sometimes called), you can find a lot of information about this very important concept in the web, including this site.
All this put together: creating a Connection object will create a new thread; in this thread, a new database connection will be established and a query will be executed, while the main thread remains free for whatever other use (for instance, managing the GUI). When the Connection object is finally destroyed, the main thread will wait for the additional thread to finish (if necessary) and then normal execution will continue. I hope this is what you wanted to accomplish with your code.

As you may evince from cppreference, std::thread's constructor expect some form of function; you can pass it a free function, a static member function or one of these packed together with its arguments by means of std::bind. In order to execute a non-static member function you should use std::mem_fn to pass it together with the object it should be called on.

Related

Why do I get "Segmentation fault (core dumped)" error when trying to implement multithreading in c++?

I have a main file where I plan to initiate the threads for my c++ program, for now, I only want to get one of the threads up and running before moving on to the others, but that is proving to be difficult. The purpose of the threads is for a TCP Server and Client to run at the same time, I have already tested my TCP code and it works, the issue now is running each one in its own thread. The following shows my main.cpp code:
#include <thread>
#include <iostream>
#include <functional>
#include "./hdr/tcpip_server.hpp"
#include "./hdr/tcpip_client.hpp"
using namespace std;
tcpServer *backendServer;
//This is done because the callback function of std::thread tcpip_server_thread complains when I only use 'backendServer->Monitor' as my callback function
void StartThread (void) {backendServer->Monitor();}
int main (void)
{
/*Initiate and start TCP server thread*/
std::thread tcpip_server_thread; // done to define object to be used outside the scope of the if statement below
if (backendServer->Init())
{
std::thread tcpip_server_thread (StartThread);
}
/*Initiate and start data reader thread*/
//std::thread tcpip_client_thread (tcpip_client);
tcpip_server_thread.join();
//tcpip_client_thread.join();
return 0;
}
The backendServer class is as follows:
class tcpServer
{
private:
int listening;
sockaddr_in hint;
sockaddr_in client;
socklen_t clientSize;
int clientSocket;
char host[NI_MAXHOST];
char service[NI_MAXSERV];
char buf[4096];
public:
bool Init ();
void Monitor ();
};
The only error I am getting with this code is the one in the title, and I only get it when the code is executing, no errors are received while compiling the code.
When trying the following:
std::thread tcpip_server_thread (backendServer->Monitor);
I get the following warning:
a pointer to a bound function may only be used to call the function
and
no instance of constructor "std::thread::thread" matches the argument list
Any help would be appreciated as this is my first project implementing threads.
1. Initializing backendServer:
backendServer is a pointer to tcpServer, but it is uninitialized (and does not point to any valid object).
Therefore backendServer->Init(); invokes UB Undefined Behavior, and likely to crash.
If you must use a pointer you must allocate it. Better still use a smart pointer like std::unique_ptr instead.
But in your case I believe the best solution is not to use a pointer at all, and define backendServer as a local variable in main:
int main(void)
{
tcpServer backendServer;
// ...
}
This will require accessing it with backendServer. instead of backendServer->.
2. The thread issue:
At the moment, you have 2 tcpip_server_thread variables.
The 2nd one inside the if is shadowing the 1st one you have before.
When you get out of the if's scope, the 2nd tcpip_server_thread will be destroyed, and a std::thread must be joined before destruction.
Later on you attempt to join the 1st one which has not even started, causing a 2nd problem.
In order to fix it:
Inside the if, do not declare a new variable. Instead use the one you already have:
tcpip_server_thread = std::thread(StartThread);
If you made backendServer a local in main as suggested above, you can use a lambda that captures it by reference:
tcpip_server_thread = std::thread(
[&backendServer]() { backendServer.Monitor();});
//--------------^^^^^^^^^^^^^^---------------------------------
Before you join the thread check that it is joinable. In the current code this will not be the case if you didn't enter the if that started the thread:
if (tcpip_server_thread.joinable())
{
tcpip_server_thread.join();
}
A side note: Why is "using namespace std;" considered bad practice?.
The main issue of your code is an uninitialised (actually: zero-initialised) pointer:
tcpServer *backendServer;
Note that you never assign a value to! This results in (as a global variable) the pointer being initialised to nullptr, which you dereference illegally later on, e.g. at (the first time during the programme run)
if (backendServer->Init())
which most likely caused the crash. A quick and dirty fix might look as:
int main()
{
backendServer = new tcpServer(); // possibly with arguments, depending
// on how your constructor looks like
// the code you have so far
delete backendServer; // avoid memory leak!!!
return 0;
}
You spare all this hassle around manual memory management (-> explicit delete) if you use smart pointers instead, e.g. std::unique_ptr. However unless you possibly want to dynamically exchange the backend server, limit its life-time to anything else than the entire programme run or construct it with arguments that need to be retrieved/calculated within main before (none of appears pretty likely to me in given case) then you most likely are better off with a global object:
tcpServer backendServer; // note the dropped asterisk!
This way the object is created before entering main and correctly destructed after leaving.
As now no pointer any more you now refer to members via . instead of ->, i.e. backendServer.Monitor() for instance.
You actually can construct a std::thread with member function pointers, too. You need, though, to pass the object on which this member function should get called to the thread as well:
std::thread(&tcpServer::Monitor, backendServer);
This works with both functions and objects, the latter are accepted by value, though, thus if you use a global object as recommended above you might rather want to create a pointer:
std::thread(&tcpServer::Monitor, &backendServer);
// ^ (!)
// note: NOT if your variable remains a pointer!!!
This way you can actually spare the global variable entirely and create the object within main and the StartThread (actually you should better have named it RunThread) gets entirely obsolete as well.
Alternatives to are converting Monitor function into an operator() or adding such one as
void tcpServer::operator()()
{
this->Monitor();
}
which makes the object itself callable, thus you could pass it directly to the thread's constructor (std::thread(std::ref(backendServer)); with std::ref preventing the object getting copied) or using a lambda:
std::thread([&]() { backendServer.Monitor(); });
both with the same advantage as providing the member function that you can spare global variable and StartThread function.
Still your code reveals another problem:
if (backendServer->Init())
{
std::thread tcpip_server_thread(StartThread);
}
You create here a second local variable tcpip_server_thread which, as long as it exists, hides the previous one, but which runs out of scope and thus gets destructed again right after the end of the if-body!
Instead you want to assign the newly created thread to the already existing variable, which would look like:
tcpip_server_thread = std::thread(StartThread);
Actually you get nicer code if you move the entire thread-code into the if block:
// no thread code left here any more
if(backendServer->Init())
{
std::thread tcpip_server_thread(StartThread);
// start second thread here, too!
tcpip_server_thread.join();
}
// no thread code left here any more
Finally you should not join a thread that actually has failed to start. You spot this by checking if the thread is joinable
std::thread tcpip_server_thread (StartThread);
if(tcpip_server_thread.joinable())
{
// see above for correct construction!
std::thread tcpip_client_thread(tcpip_client);
if(tcpip_client_thread.joinable())
{
tcpip_server_thread.join();
}
else
{
// you might need some appropriate error handling like
// printing/logging a warning message
// and possibly stop the server thread
}
}
else
{
error handling, see above
}
To fix the code I had to do 2 things, one was to not define the tcpServer variable, backendServer, as a pointer, since I never pointed it toward an actual object of the type tcpServer.
Next, I removed the first tcpip_server_thread variable and made sure that the code that initiates ```tcpip_server_thread`` and the code that joins it is in the same scope. In the future, I will implement the std::move function as explained by #wohlstad.
My working code:
#include <thread>
#include <iostream>
#include <functional>
#include "./hdr/tcpip_server.hpp"
#include "./hdr/tcpip_client.hpp"
using namespace std;
/*All the threads*/
tcpServer backendServer;
void StartThread (void) {backendServer.Monitor();}
int main (void)
{
/*Initiate and start tcp server thread*/
if (backendServer.Init())
{
std::thread tcpip_server_thread (StartThread);
if (tcpip_server_thread.joinable())
{
tcpip_server_thread.join();
}
else
{
cout << "error";
}
}
return 0;
}

How to safely remove std::thread in ATL DLL

I wrote an ATL DLL and I have problem with std::thread witch I used to run asyn method. I implemented method that performs operations asynchronously. The problem occurs when a client tries to remove the object class in which thread already done.
This is my code:
STDMETHODIMP CQRCodeGenerator::GenerateAsync(QRCodeTypeEnum QRCodeType, QRCodeFormatEnum QRCodeFormat, LONG QRCodePx, BSTR ImageFile)
{
if (ImageFile == nullptr) ImageFile = L"";
//stack to log file
OPFHelper::add_execute_method(this, L"CQRCodeGenerator::GenerateAsync",
std::vector<std::wstring>{OPFHelper::ConvertToWSting((LONG)QRCodeType),
OPFHelper::ConvertToWSting((LONG)QRCodeFormat), OPFHelper::ConvertToWSting((LONG)QRCodePx), ImageFile});
t = std::thread(&CQRCodeGenerator::run, this, QRCodeType, QRCodeFormat, QRCodePx, ImageFile);
return S_OK;
}
void CQRCodeGenerator::run(enum QRCodeTypeEnum QRCodeType, enum QRCodeFormatEnum QRCodeFormat, LONG QRCodePx, BSTR ImageFile)
{
......
Fire_OnGenerate(this,ImageFile, _pQRCode, _pInvoiceID, _pQRCodeMD5, _pKS,nullptr);
}
std::thread is declared in .h file
when I reception event and I try delete obj QRCodeGenerator I get error.
I know that this is a problem with the removal of the thread of memory, because I carried out synchronous function Generate which did not give error.
But I don't know how Can I delete this thread and detect when Client wants to delete obj. The second thing it can not understand why there is a problem with releasing memory when thread-assistant no longer works.
Do you call std::thread::join() or detach() before destroying the thread? Otherwise the std::thread destructor is supposed to trigger terminate() and abort the program.
If something is owning the thread (as "client tries to remove the object class in which thread already done" suggests), the object might call t.join() in its destructor, for example.
Also note that you shouldn't destroy the object inside of Fire_OnGenerate - that is called in the scope of the running thread. So you would basically destroy a thread which is still running (it only can complete after Fire_OnGenerate returns back).

C++ std::thread of a member function

I'm trying to program a command line server that would receive information from a serial port, parse it, and record it in an internal object.
Then upon request from a client the server would return the requested information.
What I want to do is put the receiver & parser parts in a separated thread in order to have the server running along side, not interfering with the data collection.
#include <iostream>
#include <thread>
class exampleClass{
std::thread *processThread;
public void completeProcess(){
while(1){
processStep1();
if (verification()){processStep2()}
}
};
void processStep1(){...};
void processStep2(){...};
bool verification(){...};
void runThreaded();
} // End example class definition
// The idea being that this thread runs independently
// until I call the object's destructor
exampleClass::runThreaded(){
std::thread processThread(&exampleClass::completeProcess, this);
} // Unfortunately The program ends up crashing here with CIGARET
You are running a local thread inside a member function. You have to join it or detach it and, since it is local, you have to do this in the function itself:
exampleClass::runThreaded()
{
std::thread processThread(&exampleClass::completeProcess, this);
// more stuff
processThread.join();
} //
I am guessing what you really want is to launch a data member thread instead of launching a local one. If you do this, you still have to join it somewhere, for example in the destructor. In this case, your method should be
exampleClass::runThreaded()
{
processThread = std::thread(&exampleClass::completeProcess, this);
}
and the destructor
exampleClass::~exampleClass()
{
processThread.join();
}
and processThread should be an std::thread, not a pointer to one.
Just a note on design: if you are to have a runThreaded method acting on a thread data member, you have to be very careful about not calling it more than once before the thread is joined. It might make more sense to launch the thread in the constructor and join it in the destructor.
Thread object is on stack and it is going to be destructed on function end. Thread object destructor calls std::terminate if thread still running, as in your case. See here.

Start new thread without blocking/waiting of main operation

Maybe there is a really simple solution for my problem, but I'm really confused with all the boosts around me.
Here's my problem:
I want to start a task (calculation, file system operations, etc.), raised by a callback system which calls the CallbackReceived function and I want to pass this operation to a thread, typically represented by a member function of an object. The thread isn't guaranteed to finish, so it should have something to cancel it after some time.
Something like (don't know if this is 100% correct):
// ...
MyObject object;
// ...
void CallbackReceived(int parameter) {
boost::thread tThread(&MyObject::calculate, *&object);
boost::asio::deadline_timer tDeadlineTimer(_ioService, boost::posix_time::seconds(2));
tDeadlineTimer.async_wait(boost::bind(DeadlineTimeOut, boost::asio::placeholders::error));
tThread.join();
}
Basically, a tThread.join()` waits for the return of the thread. While waiting, my main could not receive any callbacks that may come in because it's blocked and sleeps.
So what can one do, to run the thread and not to block the calling initial program while executing the operation?
You can call join just when you need the result of the calculations.
Something like "Future" pattern. Anyway, you would have to make your thread variable global to the CallBackRecieved function (You can write some wrapper).
Note: you can call join, when thread finished its' work - nothing will be blocked.
What do you want to do with the result of calculate?
Your main thread is blocked in the .join().
If you want to handle other callbacks, you have to return to the normal execution flow, waiting for another call.
Then you have to ask yourself what do you do with the result of calculate when it's finished. Maybe the thread can put the result in a shared resource somewhere and finish gracefully.
You must first sort out all what your code is supposed to do ( processing callbacks, starting threads, what to do with the result ) then you can think of implementing it. There are new constructs in boost and C++11 called promise and future that could suit you but first you have to think about what you want.
Actually you could call the callback while your main thread is sleeping. It would just run on the context (stack) of your thread.
You probably don't want to call join at the point you are at but later or never.
Example (pseudocode):
class Worker {
void doWork(void * mainthread){
Main* main = static_cast<Main*>(mainthread);
while(hasWorkTodo){
//work
//inform main
main->callbackwithinformation(information);
}
}
class Main{
atomi_int filesfound;
void main_part(){
//start worker
boost::thread thread(&Worker::doWork, &object, this);
while(hasworktodo){
//do work
//use filesfound here
}
//About to finish make sure we join our thread
thread.join();
}
void callbackwithinformation(int updatedcount){
//here we set a flag or pass some object
//probably will need an atomic operation
filesfound = updatedcount;
}
}
You would define the implementations in cpp and the interface in a h file so no circular dependency would arise, since you are only using Main as a argument in the interface a forward declaration would suffice.
//worker.h
class mainthread;
class Worker {
void doWork(void * mainthread);
}
//worker.cpp
#include "main.h"
void Worker::doWork(/* and so on*/}
//main.h
class Main{
atomi_int filesfound;
void main_part();
void callbackwithinformation(int updatedcount);
}
//main.cpp
//no need for worker.h here
void Main::main_part() /* implementation and so on */

How to pass parameters to a Thread object?

I'm working with a C++ class-library that provides a Thread base-class where the user has to
implement a run() method.
Is there a recommended way on how to pass parameters to that run() method? Right now
I prefer to pass them via the constructor (as pointers).
I'm not sure about C++, but that's how you would do it in Java. You'd have a class that extends Thread (or implements Runnable) and a constructor with the parameters you'd like to pass. Then, when you create the new thread, you have to pass in the arguments, and then start the thread, something like this:
Thread t = new MyThread(args...);
t.start();
Must be the same in your case.
An alternative is to extend this Thread class to accept a functor as only constructor parameter, so that you can bind any call inside it.
Then the class using threads wont need to inherit from Thread, but only have one (or more) Thread member. The functor calls any start point you want ( some method of the class with any parameters )
Here is a typical pattern:
1) Define a data structure that encapsulates all the data your thread needs
2) In the main thread, instantiate a copy of the data structure on the heap using operator new.
3) Fill in the data structure, cast the pointer to void*, pass the void* to the thread procedure by whatever means you are provided by your thread library.
4) When the worker thread gets the void*, it reinterpret_cast's it to the data structure, and then takes ownership of the object. Meaning when the thread is done with the data, the thread deallocates it, as opposed to the main thread deallocating it.
Here is example code you can compile & test in Windows.
#include "stdafx.h"
#include <windows.h>
#include <process.h>
struct ThreadData
{
HANDLE isRunning_;
};
DWORD WINAPI threadProc(void* v)
{
ThreadData* data = reinterpret_cast<ThreadData*>(v);
if( !data )
return 0;
// tell the main thread that we are up & running
SetEvent(data->isRunning_);
// do your work here...
return 1;
}
int main()
{
// must use heap-based allocation here so that we can transfer ownership
// of this ThreadData object to the worker thread. In other words,
// the threadProc() function will own & deallocate this resource when it's
// done with it.
ThreadData * data = new ThreadData;
data->isRunning_ = CreateEvent(0, 1, 0, 0);
// kick off the new thread, passing the thread data
DWORD id = 0;
HANDLE thread = CreateThread(0, 0, threadProc, reinterpret_cast<void*>(data), 0, &id);
// wait for the worker thread to get up & running
//
// in real code, you need to check the return value from WFSO and handle it acordingly.
// Here I assume the retval is WAIT_OBJECT_0, indicating that the data->isRunning_ event
// has become signaled
WaitForSingleObject(data->isRunning_,INFINITE);
// we're done, wait for the thread to die
WaitForSingleObject(thread, INFINITE);
CloseHandle(thread);
return 0;
}
A common problem with thread startup is that the arguments passed exist on only the stack in the calling function. Thread startup is often deferred, such that the calling function returns and it is only some time later the thread actually starts - by which time the arguments are no longer in existence.
One solution to this is to create an event and then start the thread, passing the event as one of the arguments. The starting function then waits on the event, which is signalled by the thread when it has completed startup.
You can pass the parameters as members of the thread class. The thread which creates the thread can presumably call other methods and/or call member functions before the thread starts. Therefore it can populate whatever members are necessary for it to work. Then when the run method is called, it will have the necessary info to start up.
I am assuming that you will use a separate object for each thread.
You would normally put all the threads you create into an array, vector etc.
It is ok to pass them via constructor. Just be sure that pointers will live longer than the thread.
Well, I'd prefer to put the parameters in the Start() method, so you can have a protected constructor, and doesn't have to cascade the parameters through derived class constructor.
I'd prolly let my decleration look something like this:
class Thread
{
public:
virtual void Start(int parameterCount, void *pars);
protected:
Thread();
virtual void run(int parameterCount, void *pars) = 0;
}
Just make sure that your parameters are somehow contracted, e.g. #1 will be int, #2 will be a double etc. etc. :)