1

I am not able to figure out why output of the code is 10. I have created one function printA that excepts int as const reference, from main I have created one thread and called printA, thread is kept to sleep for 20 secs so that variable a is modified by main thread.

But still output is

value of a changed
10
#include <iostream>
#include <thread>
#include<unistd.h>     
using namespace std;

void printA(const int& a)
{
    sleep(20);
    cout<<a;
}

int main()
{
    int a = 10;
    std::thread t(printA, a);
    a = 20;
    cout<<"value of a changed"<<endl;
    t.join();
}

Any help is very much appreciated.

  • 3
    "The arguments to the thread function are moved or copied by value. If a reference argument needs to be passed to the thread function, it has to be wrapped (e.g. with std::ref or std::cref)." – vvv444 May 25 '23 at 06:02
  • 1
    Also note that there's currently no synchronization. If both threads are using the same `a`, then you should protect it with a mutex. Otherwise you are potentially wide open for data races, instruction reordering, caching, _etc_. – paddy May 25 '23 at 06:12
  • A better title for this question might be 'How do threads work?'. – john May 25 '23 at 06:31

0 Answers0