什么是多线程? [英] What is multithreading?

查看:90
本文介绍了什么是多线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对什么是多线程感到很好奇.我在StackOverflow上收到的答案中听到这个名字到处都是,但是我不知道它是什么,所以我主要的两个问题是它是什么,以及如何从中受益?

I'm very curious in what multithreading is. I have heard the name battered around here and there in answers I have received on StackOverflow but I have no idea what it is, so my main two questions being what is it and how can I benefit from it?

好吧,由于第一个问题并未真正得到我一直在寻找的答案,因此我将继续进行下去.

Ok, since the first question didn't really get the response I was looking for I'll go with this..

即使在其他语言中,我也从未听说过线程".这是我在互联网上找到的一个示例:

I have never heard of 'threading' even in other languages. This is an example I have found on the internet:

#!/usr/bin/perl

use strict;
use warnings;
use threads;
use threads::shared;

print "Starting main program\n";

my @threads;
for ( my $count = 1; $count <= 10; $count++) {
        my $t = threads->new(\&sub1, $count);
        push(@threads,$t);
}
foreach (@threads) {
        my $num = $_->join;
        print "done with $num\n";
}
print "End of main program\n";

sub sub1 {
        my $num = shift;
        print "started thread $num\n";
        sleep $num;
        print "done with thread $num\n";
        return $num;
}

我似乎无法理解它在做什么.有人可以发光吗? 问候, 菲尔

I cant seem to understand what it is that it is doing. Could anyone shine any light? Regards, Phil

推荐答案

线程是一种至少在概念上(在单核单CPU计算机上,可能具有一个ARM或Atom,一次只有一个执行线程.

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

Perl示例同时启动了十个不同的代码部分.每个代码块只需要照顾自己在做什么,而不必担心其他任何事情.这意味着您可以以一种相当简单的方式使用一个称为十次的简单子例程来获得Perl程序的输出.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆