0

Why detached thread is not updating file

Hi Please refer code below: https://www.sololearn.com/compiler-playground/cNp2dN014eBP It works fine and update test.txt file when thread is joined using join(). Also, it blocks main thread until it completes writing into file. When I change join() to detach(), it does not update the file test.txt. Why it is not continuing process and update the file without asking main thread to wait? I thought detach just does not block the calling thread , but do complete the task on its own. Is this not correct? https://code.sololearn.com/cNp2dN014eBP/?ref=app

14th Nov 2023, 1:57 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
3 Respostas
+ 2
Ketan Lalcheta When you use `detach()` on a thread, it allows the detached thread to continue its execution independently of the main thread. However, in your code, after the `thread t1` is created and `t1.join()` is called, the main thread reaches the end of its execution, terminating the program. If the detached thread is still executing, it might be prematurely terminated along with the main thread, potentially preventing it from completing the file updates. To ensure the detached thread completes its task, you should introduce a delay or a mechanism to allow it sufficient time to finish its execution before the program terminates. This can be achieved by adding a sleep or using a synchronization mechanism. Keep in mind that using `detach()` requires careful management of the thread's lifetime to avoid premature termination.
18th Nov 2023, 4:55 AM
Imara Mohideen
Imara Mohideen - avatar
+ 1
Please send the code correctly.
14th Nov 2023, 3:15 PM
Imara Mohideen
Imara Mohideen - avatar
0
It was reference of code attached from web version of solo learn. Added code reference from android app as well now. Hope it is accessible.
14th Nov 2023, 4:29 PM
Ketan Lalcheta
Ketan Lalcheta - avatar