简体   繁体   中英

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?

  • Apple LLVM version 10.0.1 (clang-1001.0.46.3)
  • Target: x86_64-apple-darwin18.2.0
  • Thread model: posix
#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

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).

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 , ie don't do it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM