What is the difference between running two blocks of code on the same thread and running them on two synchronous threads?

softwareengineering.stackexchange https://softwareengineering.stackexchange.com/questions/322890

Question

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

Était-ce utile?

La solution

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.

Licencié sous: CC-BY-SA avec attribution
scroll top