From 02f9b5d0e4f45614736f59fe139267475571ec63 Mon Sep 17 00:00:00 2001 From: granbestiapop Date: Tue, 16 Jun 2020 21:34:16 -0300 Subject: [PATCH] examples: concurrency examples --- examples/concurrency/concurrency.v | 21 ++++++++++++++++ examples/concurrency/concurrency_http.v | 32 +++++++++++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 examples/concurrency/concurrency.v create mode 100644 examples/concurrency/concurrency_http.v diff --git a/examples/concurrency/concurrency.v b/examples/concurrency/concurrency.v new file mode 100644 index 0000000000..592e799883 --- /dev/null +++ b/examples/concurrency/concurrency.v @@ -0,0 +1,21 @@ +import sync +import time + +// Simulate expensive computing using sleep function +fn expensive_computing(id, duration int, wg &sync.WaitGroup) { + println('Executing expensive computing task (${id})...') + time.sleep_ms(duration) + println('Finish task ${id} on ${duration} ms') + wg.done() +} + +fn main() { + wg := sync.new_waitgroup() + wg.add(3) + go expensive_computing(1, 100, wg) + go expensive_computing(2, 500, wg) + go expensive_computing(3, 1000, wg) + // Join all tasks + wg.wait() + println('All jobs finished!') +} diff --git a/examples/concurrency/concurrency_http.v b/examples/concurrency/concurrency_http.v new file mode 100644 index 0000000000..c0501275f4 --- /dev/null +++ b/examples/concurrency/concurrency_http.v @@ -0,0 +1,32 @@ +import net.http +import sync +import time + +fn vlang_time(wg &sync.WaitGroup) ?string { + start := time.ticks() + data := http.get('https://vlang.io/utc_now')? + finish := time.ticks() + println('Finish getting time ${(finish-start)} ms') + println(data.text) + wg.done() + return data.text +} + +fn remote_ip(wg &sync.WaitGroup) ?string { + start := time.ticks() + data := http.get('https://api.ipify.org')? + finish := time.ticks() + println('Finish getting ip ${(finish-start)} ms') + println(data.text) + wg.done() + return data.text +} + +fn main() { + wg := sync.new_waitgroup() + wg.add(2) + // Run tasks async + go vlang_time(wg) + go remote_ip(wg) + wg.wait() +}