Skip to content

Instantly share code, notes, and snippets.

@spiiin
Last active September 17, 2022 08:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spiiin/b924517f1c0db7f1e08d9f7e9e2512fa to your computer and use it in GitHub Desktop.
Save spiiin/b924517f1c0db7f1e08d9f7e9e2512fa to your computer and use it in GitHub Desktop.
require daslib/coroutines
require daslib/jobque_boost
require fio
typedef
ValueOrReady = variant<value:int; ready:bool>
struct Answer
value:int
def work_in_thread(var channel: Channel?)
new_thread <| @
for i in range(100)
if i % 10 == 0
channel |> push_clone([[Answer value=i]])
sleep(10u)
channel |> append(1) //create buffer to inform that channel finish send data increase size to satisfy assert inside channel::release
channel |> release //we need to call release satisfy the condition of the ChannelAndStatusCapture macro
//completion |> notify_and_release //for thread completion logic
[coroutine]
def makeLongCalculationInThread(work) : ValueOrReady
var channel : Channel?
unsafe { channel = channel_create(); }
invoke(work, channel)
while channel.size == 0 // channel.size==1 is a signal to stop receiving
sleep(10u)
var answer: ValueOrReady
if !channel.isEmpty
let void_data = _builtin_channel_pop(channel)
unsafe
let typed_data = reinterpret<Answer?#> void_data
answer = [[ValueOrReady value = typed_data.value]]
else
answer = [[ValueOrReady ready = false]]
yield answer
unsafe { channel_remove(channel); }
[export]
def main
for num in makeLongCalculationInThread(@@work_in_thread)
if num is value
print("{num as value} ")
//Output (async):
//0 10 20 30 40 50 60 70 80 90
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment