I'm trying my hand at asynchronous function calls in C++ using std::async
in accordance with this official cplusplus.com sample code.
Unfortunately, compilation fails. When running mingw32-make
, I get the following errors:
main.cpp:37:23: error: variable 'std::future<bool> the_future' has initializer but incomplete type
main.cpp:37:61: error: invalid use of incomplete type 'class std::future<bool>'
I also tried running make
through WSL (Windows Subsystem for Linux), which essentially makes Linux bash available on Windows. Doesn't work on there either:
main.o: In function `std::thread::thread<std::__future_base::_Async_state_impl<std::thread::_Invoker<std::tuple<bool (*)(int), long> >, bool>::_Async_state_impl(std::thread::_Invoker<std::tuple<bool (*)(int), long> >&&)::{lambda()#1}>(std::__future_base::_Async_state_impl<std::thread::_Invoker<std::tuple<bool (*)(int), long> >, bool>::_Async_state_impl(std::thread::_Invoker<std::tuple<bool (*)(int), long> >&&)::{lambda()#1}&&)':
/usr/include/c++/7/thread:122: undefined reference to `pthread_create'
I've tried the following:
Updating my compiler using this SO answer.
As noted above, attempting to make using two different approaches. Both fail.
Using
gcc
instead ofg++
(just a different compiler).
Here is main.cpp
:
#include <iostream>
#include <string>
#include <cstdlib>
#include <future>
// a non-optimized way of checking for prime numbers
bool is_prime (int x)
{
std::cout << "Calculating. Please, wait..." << std::endl;
for (int i=2; i<x; ++i)
{
if(x % i == 0) return false;
}
return true;
}
void interpret_result (bool result)
{
if (result)
{
std::cout << "It is prime!" << std::endl;
}
else
{
std::cout << "It is not prime!" << std::endl;
}
}
int main()
{
long num = 313222313;
// The result of the asynchronous call to is_prime will be stored in the_future
std::future<bool> the_future = std::async (is_prime, num);
std::cout << "Checking whether " << num << " is a prime number!" << std::endl;
// Nothing beyond this line runs until the function completes
bool result = the_future.get();
// Interpret the result
interpret_result (result);
// So the cmd window stays open
system ("pause");
return 0;
}
And here is my makefile (I like to create one for each project just to practice):
COMPILER = g++
COMPILER_FLAGS = -std=c++17 -Wall -g
LINKER_FLAGS =
EXECUTABLE = async
all: main clean
main: main.o
$(COMPILER) $(LINKER_FLAGS) -o $(EXECUTABLE) main.o
main.o: main.cpp
$(COMPILER) $(COMPILER_FLAGS) -c main.cpp
.PHONY: clean
clean:
rm *.o
I'm not sure why this code isn't compiling. I've run through it and cannot identify any errors. mingw
updated successfully (I restarted my terminal afterwards).
Any help would be appreciated.