Reputation: 463
I'm compiling a block of code that contains a
std::thread::thread(Fp fp&&__, Args &&...__args)
function that, as described in the documentation c++ reference, performs the following:
(2) initialization constructor Construct a thread object that represents a new joinable thread of execution. The new thread of execution calls fn passing args as arguments (using decay copies of its lvalue or rvalue references). The completion of this construction synchronizes with the beginning of the invocation of this copy of fn.
I suppose this means "the thread will execute function Fn after it is constructed".
However I meet a Semantic Issue during compile time, saying "Attempt to use a deleted function" in the library source file thread at the following line:
__invoke(_VSTD::move(_VSTD::get<0>(__t)), _VSTD::move(_VSTD::get<_Indices>(__t))...);
I'm using LLVM C++ std library with C++ 11 support on XCode, Mac OS. I know this std::thread class is a C++ 11 feature and won't work on C++ 98. Any suggestions for making the code compilable? Pointing out of bad use of the C++ functions or classes is also appreciated.
My code is trying to perform a timerThreadTask each time a port event is received. The timerThreadTask will perform callBackFunc after a given sleep length, but will not do so if next port event happens before the sleep times out:
#include <iostream>
#include <thread>
#include "unistd.h"
using namespace std;
thread *timerThread;
bool interrupted = false;
void callBackFunc(int anyParam) {
// Perform your timeout handling
cout << "Callback handling with parameter input " << anyParam << endl;
}
void timerThreadTask(int sleepLengthInMilliSec, void *callBackFuncPtr(int anyParam)) {
// Thread procedures
int counter = 100;
int sleepIntervals = sleepLengthInMilliSec / counter;
while (counter-- > 0) {
if (interrupted == true) { // Interrupted
cout << "Sleep interrupted because a new port event is received." << endl;
interrupted = false; // Kill thread
delete timerThread;
timerThread = NULL;
return;
}
usleep(sleepIntervals);
}
callBackFuncPtr(10); // Timeout, execute callback
}
void onPortEventReceived() {
// If a message is received in time, then a thread
// will still be executing. The timer is to be
// restarted.
if (timerThread != NULL) {
interrupted = true;
}
int sleepLengthInMilliSec = 1000; // Set timer
// Starts a timer thread (**** When this line is commented, the compile will success but this will surely be meaningless)
timerThread = new thread(timerThreadTask, sleepLengthInMilliSec, callBackFunc);
}
Upvotes: 0
Views: 865
Reputation: 137315
void timerThreadTask(int sleepLengthInMilliSec, void (*callBackFuncPtr)(int anyParam))
// ^ ^
Without the parentheses, void *callBackFuncPtr(int anyParam)
is a function type (function taking int
and returning void *
) that is then transformed into a function pointer type in a function's parameter list, with the wrong return type (void *
instead of void
).
Upvotes: 1