What is multithreading? [closed]

只愿长相守 提交于 2019-12-01 14:40:00

Threading is a way of having more than one thing happen at the same time, at least conceptually speaking (on a single-core single-CPU computer, perhaps with an ARM or Atom, there's only one thread of execution at a time).

The Perl example launches ten different sections of code simultaneously. Each chunk of code only has to take care of what it is doing, and doesn't have to worry about anything else. This means you can get the output of the Perl program with one simple subroutine called ten times in a reasonably simple fashion.

One use is in programs that interact with the user. It's typically necessary to have a responsive interface along with things happening behind the scenes. It's hard to do this in one lump of code, so often the interface will be in one thread and the behind-the-scenes stuff in other threads, so that the interface can be snappy and the background tasks running.

If you're familiar with running multiple processes, threads are very similar, although they're more closely connected. This means it's easier to set up and communicate between threads, but it's also easy to mess up by not allowing for all possible orders of execution.

It is like forking, but lighter weight and it is easier to share data between threads than between processes. The downside is that, because of the sharing of data, it is easier to write buggy code (thread a modifies something thread b thought should stay the same, thread a gets a lock on resource c and tries to get a lock on resource d, but thread b has a lock on resource d and is trying to get a lock on resource c, etc.).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!