0

Suppose I have two blocks of code, A and B. A is to be executed before B. As I understand, I can do one of two things: 1) Put B in a separate thread that is to be executed after A's thread, or 2) Put A and B in the same thread, with A preceding B in the order of execution.

Option #1 means more memory will be allocated for B's thread, while Option #2 means only the memory needed by B will be allocated.

What I'm really looking for is an objective assessment of why one might prefer option #1 over option #2 (and vice versa).

8
  • One (great) reason to use threads is so you don't have to write your own scheduling system to have code A and code B run in parallel. This is useful when your threads are long running and A and B have really nothing to do with eachother.
    – MetaFight
    Jun 21, 2016 at 20:38
  • 4
    If you're not going to execute them simultaneously, why would you need two threads? Jun 21, 2016 at 20:39
  • @Robert Harvey: Sometimes we can run two threads asynchronously, which I'm assuming means we run B's thread after A's thread.
    – moonman239
    Jun 22, 2016 at 5:53
  • @moonman239: Asynchronous execution typically means independent execution. If one thread always has to wait for another thread to finish before it can start doing work, there are no advantages to using multiple threads. Jun 22, 2016 at 7:12

1 Answer 1

1

The way your question is written makes using multiple threads seem pretty much pointless. However, a couple of examples where you might do this that are similar to what you describe.

TIMEOUTS - If you don't want A to take longer than some specific amount of time then you'd possibly start B running on a separate thread while thread A is waiting for a response or waits long enough to timeout.

HARDWARE/DESIGN- Frequently when communicating with various hardware devices you'll have one or more threads dedicated to communicating to that particular device. This allows for commands and status to be handled fairly seamlessly without the rest of the application needing to care about threading issues with the hardware. For a typical command, the call from A would queue a command, when the hardware is ready to process the next command it removes the command from the queue and executes on its own thread B. In the meantime A would block until the command is finished. There are also times where it might be desirable for a software module to behave this way, such as a logging module.

1
  • You might want to emphasize that option 2 is the best one usually, and that the difference is a shared stack. Jun 23, 2016 at 23:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.