samedi 20 avril 2019

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 am deleting that memory before new 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

Aucun commentaire:

Enregistrer un commentaire