Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread.start immediately followed by Thread.join - is it useful?

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?

like image 591
luiges90 Avatar asked Nov 12 '12 13:11

luiges90


2 Answers

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

like image 125
jalf Avatar answered Nov 10 '22 00:11

jalf


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:

  • Your thread have another security context, but you want to execute in default. Impersonation can cost near the same processor time as allocate thread from pool
  • Your thread has bigger (or lower for some-time) priority then current - so critical small part of code can be executed in near-the-runtime. For low-priority you assume some big wait (from user input for example)
like image 25
Dewfy Avatar answered Nov 09 '22 23:11

Dewfy