examples: concurrency examples

pull/5401/head
granbestiapop 2020-06-16 21:34:16 -03:00 committed by GitHub
parent 88654ad81b
commit 02f9b5d0e4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 53 additions and 0 deletions

View File

@ -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!')
}

View File

@ -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()
}