Back from the Future

Test your C++ programming skills by solving the given puzzle about data races and the importance of thread-safe operations.

Puzzle code

Carefully read the code given below:

Press + to interact
#include <future>
#include <iostream>
int main()
{
char counter = 0;
auto future1 = std::async(std::launch::async, [&]()
{
counter++;
});
auto future2 = std::async(std::launch::async, [&]()
{
return counter;
});
future1.wait();
// Cast to int to print it as a numerical value rather than a character
std::cout << (int)future2.get();
}

Your task: Guess the output

Try to guess the output of the above code. Attempt the following quiz to assess your understanding.

Q

What is the expected output of the above code?

A)

0

B)

1

C)

Undefined behavior

D)

Runtime error

Let’s discuss this code and output together in the next lesson.

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.