examples: concurrency examples
parent
88654ad81b
commit
02f9b5d0e4
|
@ -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!')
|
||||
}
|
|
@ -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()
|
||||
}
|
Loading…
Reference in New Issue