I come across with such code in many places in a project written by others, and I am still puzzled why somebody would write such code.
Consider the following code (this code is in C# but I think it applies to many languages too - possibly just with difference on syntax or maybe names of the classes and the way of doing this - you get the idea.):
Thread thread;
thread = new Thread(new ThreadStart(method));
thread.Start();
thread.Join();
To my understanding, this code means start a thread and runs method
, and then this thread wait, without doing any other things, for the newly started thread to finish.
If it is the case, why I don't just call the method directly, i.e.
method()
Could anyone explain to me if my understanding is right or not? Does the first code fragment does functionally the same as the second?
usually, you're right, this is not a very useful thing to do.
But sometimes, you may want an operation to run on a separate thread, because it modifies or depends on some per-thread state.
The function may be fiddling with thread-local data, or it might call out into native COM code, and COM's threading apartment stuff is initialized on a per-thread basis, so to avoid this being affected by changes in the calling code, you may want to just spin off a new thread to call the function on.
Of course, in such cases, a small code comment explaining why something so apparently useless is being done, would probably be a good idea. ;)
Functionally both piece of code are the same. Threads case is just delegation of invocation to high price. But exists some cases when it can be helpful:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With