Reputation: 3960
// The function that the background thread will run
void runPingThread(std::promise<int>& promiseObj) {
while (!stopFlag) {
ping(); // Call the ping function
std::this_thread::sleep_for(std::chrono::seconds(5)); // Poll every 5 seconds
int result = 42;
// Set the value in the promise object
promiseObj.set_value(result);
}
}
// Initialize the service and start the ping thread
void init() {
// Step 1: Create a promise object
std::promise<int> promiseObj;
// Step 2: Get a future object associated with the promise
std::future<int> futureObj = promiseObj.get_future();
// Step 3: Create a thread and pass the promise object
pingThread = std::thread(&ConnectionService::runPingThread, std::ref(promiseObj));
// Step 4: Wait for the result from the thread using future
std::cout << "Waiting for result from thread..." << std::endl;
int result = futureObj.get(); // Blocks until the value is set in the promise
// Step 5: Print the result
std::cout << "Result from thread: " << result << std::endl;
/*
// Start the pinging thread
pingThread = std::thread(&ConnectionService::runPingThread, this);
std::cout << "Ping service started..." << std::endl;*/
}
I am getting error 1>C:\Program Files\Microsoft Visual Studio\2022\Professional\VC\Tools\MSVC\14.41.34120\include\thread(60,14): error C2672: 'invoke': no matching overloaded function found
Both functions are inside class ConnectionService
Upvotes: 0
Views: 23