How can multithreading speed up an application (when threads can't run concurrently)?

前端 未结 9 1986
忘掉有多难
忘掉有多难 2020-12-31 09:11

I\'m learning about multithreading, but after reading some tutorials I\'m sort of confused. I don\'t understand how multithreading can speed up an application.

By in

9条回答
  •  独厮守ぢ
    2020-12-31 09:56

    One of the most important uses of multithreading is in GUI programming. If you only had a single thread, what happens when you click a button? You would have to wait for whatever action that button fired to complete before control returned to the GUI. To put that in context. If your browser only ran in a single thread and you wanted to download say, a Linux ISO, you're entire browser would be unusable for the duration of the download as the single thread would be taken up with the download and wouldn't be available to respond to user actions. You couldn't even cancel the download.

    By using multiple threads, you can continue using your browser while the download occurs in the background.

    There are plenty of other uses that can speed up a program. For example, searching a large dataset. You can divide it up into chunks and each thread can search a chunk. You can then join on those threads completing and collect the results.

    Also, semaphores aren't always necessary. It depends on what you're doing. If you have multiple threads consuming tasks from a single work queue, you want to make sure a job is removed from the queue before another thread can request a job so that you're not assigning the same work to 2 threads. In that case you use semaphores to make your work queue "thread safe". On the other hand, hootsuite or one of those other social media desktop clients could (don't know if they do) run a thread for each platform you're connected to so that you can fetch updates from multiple platforms in parallel.

提交回复
热议问题