+ 1

Why Detach and Ref is working

Hi Refer code below: It is okay and works as expected. Just change the last line of void testmethod() from t2.join(); to t2.detach(); This new modification should not throw exception? I thought that it should and reason is as below: testmethod has x defined which is used in reference by testmethod2 As we have t2.detach() , it is not blocking testmethod to exit until testmethod2 is not completed. Isn't it result into access of x inside testmethod2 throwing exception as x is no longer available? https://code.sololearn.com/cQA83nYOQ87g/?ref=app

25th Dec 2022, 6:52 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
2 ответов
+ 2
Premise: When you calls some function, all local variblables will be "allocated" onto stack memory which is placed on top all current stack memory (caller function and so on). In memory is memorized current last adress of this stack and, when function call ends, this adress is "setted" to be ad end of previous stack (caller function stack). Its important understand that local variable of terminated functions are not destroyed in memory contect BUT them can be overwrited from another stack creation (another function call that overwrite enought memory). As consequence its bad use a reference to a local variable to a terminated function BUT while the adress onto stack is not overwrited, all works. Another things to understand is that a thread create a own stack memory indipendent from other threads. In practice: never do this because make you program very underterministics and hard to debug
25th Dec 2022, 11:40 PM
KrOW
KrOW - avatar
+ 3
Thanks
26th Dec 2022, 4:23 AM
Ketan Lalcheta
Ketan Lalcheta - avatar