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

前端 未结 8 1632
南旧
南旧 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:38

    Came across this post. Interesting discussion. but I felt one point is missing or indirectly pointed.

    Creating a new process is costly because of all of the data structures that must be allocated and initialized. The process is subdivided into different threads of control to achieve multithreading inside the process.

    Using a thread or a process to achieve the target is based on your program usage requirements and resource utilization.

    0 讨论(0)
  • 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.
    0 讨论(0)
提交回复
热议问题