From f3a9e2a3418b2ad818713938a770ffe93fb0e0c9 Mon Sep 17 00:00:00 2001 From: Alexander Medvednikov Date: Sat, 22 Jun 2019 21:51:07 +0200 Subject: [PATCH] update the news fetcher example --- examples/concurrent_news_fetcher.v | 35 -------------------- examples/news_fetcher.v | 52 ++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 35 deletions(-) delete mode 100644 examples/concurrent_news_fetcher.v create mode 100644 examples/news_fetcher.v diff --git a/examples/concurrent_news_fetcher.v b/examples/concurrent_news_fetcher.v deleted file mode 100644 index faca945e15..0000000000 --- a/examples/concurrent_news_fetcher.v +++ /dev/null @@ -1,35 +0,0 @@ -// Please share your thoughts, suggestions, questions, etc here: -// https://github.com/vlang-io/V/issues/3 -// I'm very interested in your feedback. -import http -import json -import runtime - -struct Story { - title string -} - -// Fetches top HN stories in 8 coroutines -fn main() { - resp := http.get('https://hacker-news.firebaseio.com/v0/topstories.json')? - ids := json.decode([]int, resp.body)? - mut cursor := 0 - for _ in 0..8 { - go fn() { - for { - lock { // Without this lock the program will not compile - if cursor >= ids.len { - break - } - id := ids[cursor] - cursor++ - } - url := 'https://hacker-news.firebaseio.com/v0/item/$id.json' - resp := http.get(url)? - story := json.decode(Story, resp.body)? - println(story.title) - } - }() - } - runtime.wait() // Waits for all coroutines to finish -} diff --git a/examples/news_fetcher.v b/examples/news_fetcher.v new file mode 100644 index 0000000000..4fce584991 --- /dev/null +++ b/examples/news_fetcher.v @@ -0,0 +1,52 @@ +import http +import json +import sync +import time + +const ( + NR_THREADS = 8 +) + +struct Story { + title string +} + +struct Fetcher { +mut: + mu sync.Mutex + ids []int + cursor int +} + +fn (f mut Fetcher) fetch() { + for { + f.mu.lock() + if f.cursor >= f.ids.len { + return + } + id := f.ids[f.cursor] + f.cursor++ + f.mu.unlock() + resp := http.get('https://hacker-news.firebaseio.com/v0/item/${id}.json') + story := json.decode(Story, resp) or { + exit('failed to decode a story') + } + println('#$f.cursor) $story.title') + } +} + +// Fetches top HN stories in 8 coroutines +fn main() { + resp := http.get('https://hacker-news.firebaseio.com/v0/topstories.json') + ids := json.decode( []int, resp) or { + println('failed to fetch topstories.json') + return + } + fetcher := &Fetcher{ids: ids} + for i := 0; i < NR_THREADS; i++ { + go fetcher.fetch() + } + println(fetcher.ids) + time.sleep(5) +} +