Why should I use a thread vs. using a process?

前端 未结 8 1648
南旧
南旧 2020-12-12 13:36

Separating different parts of a program into different processes seems (to me) to make a more elegant program than just threading everything. In what scenario would it make

8条回答
  •  抹茶落季
    2020-12-12 14:39

    Well apart from advantages of using thread over process, like:

    Advantages:

    • Much quicker to create a thread than a process.
    • Much quicker to switch between threads than to switch between processes.
    • Threads share data easily

    Consider few disadvantages too:

    • No security between threads.
    • One thread can stomp on another thread's data.
    • If one thread blocks, all threads in task block.

    As to the important part of your question "When should I use a thread?"

    Well you should consider few facts that a threads should not alter the semantics of a program. They simply change the timing of operations. As a result, they are almost always used as an elegant solution to performance related problems. Here are some examples of situations where you might use threads:

    • Doing lengthy processing: When a windows application is calculating it cannot process any more messages. As a result, the display cannot be updated.
    • Doing background processing: Some tasks may not be time critical, but need to execute continuously.
    • Doing I/O work: I/O to disk or to network can have unpredictable delays. Threads allow you to ensure that I/O latency does not delay unrelated parts of your application.

提交回复
热议问题