Tefone
Tefone

Reputation: 29

In C++11, how not to pass arguments to threads?

I am trying to implement the following code, but before accessing the memory corresponding to the pointer, I delete that memory in main thread. Is this an undefined behavior, but the output is normal?

#include <iostream>
#include <string>
#include <thread>
void newThreadCallback(int *p)
{
    std::cout<<"Inside Thread 1 : p = "<<p<<std::endl;
    std::chrono::milliseconds dura(1500);
    std::this_thread::sleep_for(dura);
    *p = 19;
    std::cout<<"Inside Thread 2 : *p = "<<*p<<std::endl;
}

void startNewThread2()
{
    int *p = new int(10);
    std::cout<<"Inside Main Thread : *p = "<<*p<<std::endl;
    std::cout<<"Inside Main Thread : p = "<<p<<std::endl;
    std::thread t(newThreadCallback, p);
    t.detach();
    delete p;
    p = NULL;
    //std::cout<<"Inside Main Thread : *p = "<<*p<<std::endl;
}

int main()
{
    startNewThread2();
    std::chrono::milliseconds dura(2000);
    std::this_thread::sleep_for(dura);
    return 0;
}

The output is:

Inside Main Thread : *p = 10
Inside Main Thread : p = 0x7f7f765003a0
Inside Thread 1 : p = 0x7f7f765003a0
Inside Thread 2 : *p = 19

Upvotes: 0

Views: 99

Answers (2)

rustyx
rustyx

Reputation: 85256

You can reproduce the same behavior without threads - allocate some memory, write to it, free it and then read from it - in many cases you will read your expected value.

That's because during the delete operation the memory region is marked as "free" while it's contents remains untouched. So you will read the expected value from it until it's reallocated and written to someplace else in the program. There is no way to know when that will happen, which is partly why it's undefined behavior, i.e. don't do it.

Upvotes: 0

John Zwinck
John Zwinck

Reputation: 249093

Of course that's undefined behavior. You happened to get the correct behavior on some system, but you might not always be so "lucky." An easy fix is to not pass raw pointers around (you could use unique_ptr here).

Upvotes: 2

Related Questions