D中使用for循环的多线程 [英] multithreading in D with for loop

查看:118
本文介绍了D中使用for循环的多线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道Rust可以使用轻量级线程运行循环.像这样:

I know that Rust can run loops with lightweight threads. Something like:

use task::spawn;

fn main() {
  for 100.times {
    do spawn {
      io::println("Hello");
    }
  }

我如何在D中做到这一点?

How I can do this in D?

推荐答案

相关API文档: std.parallelism

以下是完成示例的几种方法:

Here are a few of ways of accomplishing your example:

使用TaskPool的并行并行进行each :

Parallel foreach, using a TaskPool's parallel:

foreach (i, val; taskPool.parallel(new int[50])) {
    writeln("Hello:", i);
}

常规foreach,使用 put :

Regular foreach, adding tasks to a task pool using put:

foreach (i; 0 .. 50) {
    auto t = task!writeln("Hello:", i);
    taskPool.put(t);
}

新线程而不是TaskPool中执行每个任务:

Execute each task in a new thread instead of a TaskPool:

foreach (i; 0 .. 50) {
    auto t = task!writeln("Hello:", i);
    t.executeInNewThread();
}

Rust的运行时具有一个内置的任务计划程序,但是对于D,这是作为一个库实现的.话虽这么说,第二个在功能上是最接近的,最后一个在语法上是最接近的(但是它们是OS线程,而不是轻量级).

Rust's runtime has a built-in task scheduler, but with D, this is implemented as a library. That being said, the second is the closest in terms of functionality, and the last is the closest in terms of syntax (but they're OS threads, not lightweight).

在D中,轻量级线程由程序员明确控制. TaskPool与Rust/Go中的调度程序类似,但是它为程序员提供了更细粒度的控制.这使它稍微冗长一些,但同时也为您提供了mapreduceforeach等的并行版本.这使得更容易高效地表示更复杂的算法.

In D, lightweight threads are explicitly controlled by the programmer. A TaskPool is analogous to the scheduler in Rust/Go, but it gives more fine-grained control to the programmer. This makes it slightly more verbose, but it also gives you parallel versions of map, reduce, foreach, etc. This makes it easier to represent more complex algorithms efficiently.

运行每个示例都应该为您带来预期的结果:乱序写入.

Running each example should give you the expected result: out of order writes.

注意:

来自文档:

此池中的工作线程是守护程序线程,这意味着在终止主线程之前不必调用TaskPool.stop或TaskPool.finish.

The worker threads in this pool are daemon threads, meaning that it is not necessary to call TaskPool.stop or TaskPool.finish before terminating the main thread.

第二个示例不会等到所有工作人员都完成之后,因此在测试中您可能不会获得任何结果(当主要完成时,所有剩余任务都将被杀死).您可能需要通过调用完成:

The second example doesn't wait until all workers are done, so in testing you may get no results (when main finishes, all remaining tasks are killed). You may need to block by calling finish:

taskPool.finish(true);

这篇关于D中使用for循环的多线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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