-3
以下のC++コードをNode.jsに書きたいと思います。node.jsのC++ future async相当のもの
#include <iostream>
#include <future>
#include <string>
std::mutex mut;
void print(const std::string& message, int n) {
for (int i = 0; i < n; ++i) {
{
std::lock_guard<std::mutex> lk(mut);
std::cout << message << std::endl;
}
usleep(200000);
}
std::lock_guard<std::mutex> lk(mut);
std::cout << message << " finished" << std::endl;;
}
int main() {
std::future<void> fut_a = std::async(print, "a", 2);
std::future<void> fut_b = std::async(print, "b", 8);
fut_a.get();
std::future<void> fut_c = std::async(print, "c", 2);
std::future<void> fut_d = std::async(print, "d", 2);
fut_c.get();
fut_d.get();
fut_b.get();
}
出力である:BのNode.jsのB BはD = bのDのC B BはBのB
は、以下のコードは "" 終了し表示する前に "C" を表示開始v8.6.0。
const asyncfunc = (message, n) => {
for (let i = 0; i < n; ++i) {
setTimeout(() => {
console.log(message);
}, 200 * i);
}
}
async function main() {
const a = asyncfunc("a", 2);
const b = asyncfunc("b", 8);
await a;
const c = asyncfunc("c", 2);
const d = asyncfunc("d", 2);
await c;
await d;
await b;
}
main();
出力は次のようになります。B B B B B
B、B、CのD BはD上のC++のコードと同等の書き込みをNode.jsの中の任意の便利な方法はありますか?
あなた 'asyncfunc'は実際に約束を返さないので、'待つ; '何もしません。 – jtbandes
あなたはコアのJavaScriptからsetTimeoutを単に使うことができると思います – Adem
私の基本的な間違いを指摘してくれてありがとう。わかった。 – tielw