Search⌘ K

Arguments of Threads: Undefined Behavior

Explore the causes of undefined behavior when passing thread arguments by reference in C++. Understand how detached threads can lead to unexpected results and prepare to learn solutions that prevent these issues.

We'll cover the following...

As discussed in the previous lesson, here is another example of undefined behavior caused by improper handling of thread arguments.

C++
// threadArguments.cpp
#include <chrono>
#include <iostream>
#include <thread>
class Sleeper{
public:
Sleeper(int& i_):i{i_}{};
void operator() (int k){
for (unsigned int j= 0; j <= 5; ++j){
std::this_thread::sleep_for(std::chrono::milliseconds(100));
i += k;
}
std::cout << std::this_thread::get_id() << std::endl;
}
private:
int& i;
};
int main(){
std::cout << std::endl;
int valSleeper = 1000;
std::thread t(Sleeper(valSleeper), 5);
t.detach();
std::cout << "valSleeper = " << valSleeper << std::endl;
std::cout << std::endl;
}

The question is, what value does valSleeper have in line 29? ...