Masthash

#coroutines

Ben Clifford
2 weeks ago

time for some paid experimentation with Python coroutines in @ParslProject

#HPC #Coroutines

deitel
1 month ago

C++20 Fundamentals LiveLessons users: I just submitted Lesson 18, "C++20 Coroutines." I should go live at https://learning.oreilly.com/videos/c-20-fundamentals/9780136875185/ in the next couple of days.

#CPlusPlus20 #CPlusPlus #coroutines #co_await #co_yield #co_return #concurrencpp

Karsten Schmidt
2 months ago

Earlier today I released a new version of https://thi.ng/fibers aka building blocks and operators for coroutine-based multitasking and alternative to async-await. It's one of the more recent packages, but also one which is quickly cementing itself as one of the most powerful & flexible tools of the whole #ThingUmbrella collection, similar to how https://thi.ng/transducers & https://thi.ng/rstream have done in other contexts...

Recent versions have included new helpers to improve interop between fibers and async functions and to simplify time-sliced processing of child tasks and/or iterables (incl. via transducers).

The attached code snippet shows an example excerpt of how this is used in the recent (and even more recently updated) #HowToThing Mastodon UI demo. See linked toot for demo link & fully commented source code...

https://mastodon.thi.ng/@toxi/111069280667363259

#TypeScript #JavaScript #Coroutines #Async

TypeScript code snippet (from an async function) showing how to wrap a fiber/task as promise and then waiting for its execution to complete:

// load recent messages
const rawMessages = await loadJSON(
	`${baseURL}/${account.id}/statuses?limit=50&exclude_replies=true&exclude_reblogs=true`
);

// split up message parsing/transformation over several frames,
// updating progress bar at each step
const transformedMessages = asPromise<Message[]>(function* () {
	const results: Message[] = [];
    // trigger & wait for time-sliced processing
	yield* timeSliceIterable(
		// create a (lazy) iterator of transformed messages
		iterator(transformMessage, rawMessages),
		// collect step-wise results, update progress
		(chunk) => {
			results.push(...chunk);
			progress.next(results.length / rawMessages.length);
		},
		// arbitrarily limit step duration (time slice) to 1ms
		1
	);
	return results;
});

// wait for task to finish & place results (transformed messages) into
// stream to trigger UI update
messages.next(await transformedMessages);
Bahman M.
3 months ago

A good read, if a bit long, read on the topic:

📜 Philosophy of #Coroutines

🙶.. my ‘philosophy of coroutines’: why I find them so useful, what kinds of thing they’re useful for, tricks I’ve learned for getting the most out of them, and even a few different ways of thinking about them.🙷

https://www.chiark.greenend.org.uk/~sgtatham/quasiblog/coroutines-philosophy/

#Programming #Concurrency #Parallelism #Software

#Coroutines are much lighter than #Threads; But why? 🤔
What happens behind the scenes when we launch thousands of Coroutines It is okay but when does with Threads program become laggy or crash? Let's see why. 🌟

#Kotlin #Java #Loom #Android #AndroidDev

https://www.youtube.com/watch?v=hjASLkHz-8k

Great answer to the question "Can someone explain to me what #Coroutines are?"

https://www.reddit.com/r/Kotlin/comments/162d2lv/comment/jxwouwx/

#Kotlin

Uli Kusterer
3 months ago

Can a Swift async method return multiple results over time? Different types, so I don’t think I can use AsyncSequence? Something like (pseudocode)

let (showProgress: async Bool, result: async MyThing) = await doSomethingLengthy()
if await showProgress {
showProgressScreen()
}
processResult(await result)

?

doSomethingLengthy() would guarantee that doProgress is fulfilled before result, in case that helps.

Or must it be a 2-method delegate?

#swiftlang #programming #asyncAwait #coroutines

Karsten Schmidt
4 months ago

After some friendly inquiry by @computersandblues, I spent a few hours today adding basic CSP (#CommunicatingSequentialProcesses) primitives for https://thi.ng/fibers and writing some preliminary documentation. I'm amazed how simple (and easy!) it was this time around (compared to https://thi.ng/csp) and it's giving me big hopes for the fiber based approach in general...

Readme section:
https://github.com/thi-ng/umbrella/blob/develop/packages/fibers/README.md#csp-primitives-communicating-sequential-processes

2-channel ping/pong example:
https://github.com/thi-ng/umbrella/blob/develop/packages/fibers/README.md#csp-pingpong-example

Source code & doc strings:
https://github.com/thi-ng/umbrella/blob/develop/packages/fibers/src/csp.ts

#ThingUmbrella #TypeScript #Coroutines #CSP #CooperativeMultitasking

Excerpt from readme:

"CSP primitives (Communicating Sequential Processes)

In addition to the operators above, the basic fiber implementation can also be used to construct other types of primitives, like these required for channel-based communication between processes. The package includes a fiber-based read/write channel primitive which can be customized with different buffer behaviors to control blocking behaviors and backpressure handling (aka attempting to write faster to a channel than values are being read, essentially a memory management issue).
Buffering behaviors

The following channel buffer types are included, all accepting a max. capacity and all implementing the required IReadWriteBuffer interface:

fifo: First in, first out. Writes to the channel will start blocking once the buffer's capacity is reached, otherwise complete immediately. Likewise, channel reads are non-blocking whilst there're more buffered values available. Reads will only block if the buffer is empty.

lifo: First in, last out. Read/write behavior is mostly the same as with fifo, with the important difference, that (as the name indicates), the last value written will be the first value read (i.e. stack behavior).

sliding: Sliding window buffer. Writes to the channel are never blocking! Once the buffer's capacity is reached, a new write will first expunge the oldest buffered value (similar to LRU cache behavior). Read behavior is the same as for fifo.
..."
TypeScript source code (ping/pong example):

import { channel, fiber, wait } from "@thi.ng/fibers";
import { ConsoleLogger } from "@thi.ng/logger";

// create idle main fiber with custom options
const app = fiber(null, {
    id: "main",
    logger: new ConsoleLogger("app"),
    terminate: true,
});

// create CSP channels (w/ default config)
const ping = channel<number>();
const pong = channel<number>();

// attach ping/pong child processes
app.forkAll(
    // ping
    function* () {
        let x: number | undefined;
        while (ping.readable()) {
            // blocking read op
            x = yield* ping.read();
            // check if channel was closed meanwhile
            if (x === undefined) break;
            console.log("PING", x);
            // blocking write op to other channel
            yield* pong.write(x);
            // slowdown
            yield* wait(100);
        }
    },
    // pong (very similar)
    function* () {
        let x: number | undefined;
        while (pong.readable()) {
            x = yield* pong.read();
            if (x === undefined) break;
            console.log("PONG", x);
            yield* ping.write(x + 1);
        }
    },
    // channel managment
    function* () {
        // kickoff ping/pong
        yield* ping.write(0);
        yield* wait(1000);
        // wait for both channels to close
        yield* ping.close();
        yield* pong.close();
    }
);
app.run();
Josiah Winslow
4 months ago

#AGBIC Day 20

Because I'm using #coroutines everywhere, I decided to create a centralized system for them, instead of having like 4 systems that each work differently.

Now it'll be easier to run things like the #AI and the #dialog box at the same time. (Check out that box!) #pico8

#gamejam #gamedevelopment #gamedev #indiedev #programming

A pixelated Othello game with a minimalist aesthetic. Every so often, a white box drops down from the top and a test message is typed onto it.
Josiah Winslow
4 months ago

I made the simplest "dialog" system I could make in #pico8. This will be how the dark void talks to you. (Spinning orbs unrelated.)

Because it should run alongside the game, it's controlled by a coroutine. (I know, I'm overusing #coroutines, but it was easy to get this working!)

#lua #gamejam #gamedevelopment #indiedev #programming

Three orbs moving in circular paths at different speeds in different directions. Above them, the following words appear, which are descriptive of how they are displayed:

This is a dialog system test. It's not very clever, and in fact it's very poorly done.
You can make the text slow...
...or you can make it fast!
You can even make the text wait for an amount of time, instead of a button!
I don't have any more text.
Josiah Winslow
5 months ago

Yes!

I added an #animation that moves the cursor to an arbitrary location. IMHO, this makes the #AI look way more natural.

I also refactored the AI #code to use #coroutines, just like my animation system. Once the calculations start taking longer than a frame, I'll need it.

#pico8 #lua #gamejam #gamedev #gamedevelopment #indiedev #programming

A pixelated Othello game with a minimalist aesthetic.

The AI player, played by white, automatically moves the cursor to the square it wants to play on before playing on that square.
Josiah Winslow
5 months ago

#AGBIC Day 9

I have a simple animation system using #Lua #coroutines in #pico8. Right now, I added animation pausing to this system, so I could avoid having #game logic in the animation #code. This refactor makes it feel a lot less hacky.

Pic 1: before
Pic 2: after

#gamejam #gamedev #gamedevelopment #indiedev #programming

Some Lua code as viewed in the PICO-8 editor. It has a comment that reads "this is very hacky, but this is the part that prompts for user input", before some code that sets the contents of a message and waits until the user presses X.
Some Lua code as viewed in the PICO-8 editor. The part that previously waited for user input is replaced with logic that pauses the animation, and elsewhere in the code, the main game loop checks that this animation is paused. If it is paused, it sets the contents of a message and waits until the user presses X.
Jason Howard :sdf:
5 months ago

I propose #mastodon be renamed to #coroutines.

synlogic
5 months ago

as a fan of oldskool dystopic/apoc fiction & drama TV (esp from the 60s to 80s, & UK/Euro) let me just say Meta's choice of the Threads name is terrible... & PTSD-inducing

as a decades-long programmer with plenty of scars from doing & seeing multi-threaded programming at scale, well, let me just say Meta's choice of the Threads name is also terrible... & PTSD inducing

#Meta
#Threads

#programming
#multithreading
#concurrency
#parallelism
#threading
#fibers
#coroutines
#goroutines
#processes

tgfrerer
5 months ago

Can the new C++20 coroutines be put to work to replace a fiber-based job-system?
Read all about it in a new (lengthy) blog post: http://poniesandlight.co.uk/reflect/coroutines_job_system/
Comes with demo code. And a terrible herpetological simile. 🐍

#cpp #coroutines

deitel
7 months ago

New translation coming of our C++20 for Programmers book! #cplusplus20 #cplusplus #modules #concepts #coroutines #ranges #bigfour

droidcon
7 months ago

#Kotlin Structured concurrency helps cancel #coroutines, not only individually but also centralised using root coroutine. By @goodandroidev

https://www.droidcon.com/2023/04/17/applying-kotlin-structured-concurrency-part-iv-coroutines-cancellation/

Simon Racz
8 months ago

Processes, Threads, Coroutines in Various Programming Languages.

Apart from giving an overview of the topic, I compare the runtime thread count of three different codes in five languages.

A hello world application.

An app that makes three blocking HTTP GET requests.

And finally an async/coroutine/green thread solution for making those same HTTP GET requests.

I was surprised by some results. :)

https://youtu.be/ehW2dv0IPIM

Code: https://github.com/simonracz/threads-streaming

#linux #threads #processes #coroutines #go #rust #java #c++ #c #python #syscalls

droidcon
9 months ago

Expand your horizons with new #Android skills 📓

Instructor @StefanCatalin will explain how to build an #MVVM app from scratch using #JetpackCompose, #Kotlin #Coroutines, Flows, #Roomdatabase, #Retrofit, & HILT DI using MAD skills.

Shop the course: https://academy.droidcon.com/course/building-a-complete-mvvm-app-from-scratch-with-android-jetpack-compose

Simon Vergauwen
9 months ago

Don't miss the webinar on Thursday #Kotlin!

As always there is too much I want to talk about😅 Composing different #arrowkt DSLs and #KotlinX #Coroutines to running #Kotlin JVM/Native
#JetBrains #Ktor on #Kubernetes with zero-downtime.

& be sure to bring all your questions! ☺️

https://info.jetbrains.com/kotlin-webinar-february16-2023.html?utm_campaign=webinar-february16-2023

Abhinav ⁉️
10 months ago

I wrote the third part of my #blog post series: “Implementing Co, a Small Language With Coroutines #3: Adding #Coroutines”. https://abhinavsarkar.net/posts/implementing-co-3/

Reply to this toot to post comments on the article.

#programming #programminglanguages #plt #compilers #haskell #concurrency

Coa
10 months ago

What is the purpose of the withContext function in Kotlin Coroutines?

- The withContext function is used to change the context of a coroutine, for example, to switch from a background thread to the main thread. It allows you to execute code in a different thread while still preserving the current context, such as the current scope and job.

#AndroidDev #AndroidDevs #Android #kotlin #coroutines

Coa
10 months ago

What is the difference between CoroutineScope and GlobalScope in Kotlin Coroutines?

- CoroutineScope is used to define the scope for a group of related coroutines, and provides a way to cancel all the coroutines when the scope is no longer needed. GlobalScope is a predefined scope that is used for coroutines that have no specific scope, and continue to run even after the completion of the main function.

#AndroidDev #AndroidDevs #Android #kotlin #coroutines

Coa
10 months ago

What is the difference between suspend and resume in Kotlin Coroutines?

- suspend is used to pause the execution of a coroutine and return control to the caller, while resume is used to resume the execution of a suspended coroutine. Together, these two methods allow coroutines to perform tasks asynchronously, without blocking the calling thread.

#AndroidDev #AndroidDevs #Android #kotlin #coroutines

Simon Vergauwen
11 months ago

#Kotlin #Coroutines keep getting better 😍 This 1.8 feature is 🔥

> The "was optimized out" feature optimizes variables when you use suspend functions. However, it is difficult to debug code with optimized variables because you don't see their values.

https://go.jetbrains.com/NDI2LVFWRC0xMTQAAAGJRbCp8K8xYgdUlwjgvU0z7hNpmys8iROAWYHeRSPtzL8LRCzLnaNpxDb2jx3YMP9FuIbhmW8=

Thomas Keller 🇺🇦
11 months ago

TIL: Writing

fun foo() {
runBlocking {
someSuspendMethod()
}
}

for compat reasons with legacy Java code is a bad idea, since `runBlocking` will use `Thread.currentThread()` internally and that will lock the main thread forever when `foo()` is executed from there (and you'll never know on which thread you're called, right?!).

Solution:

fun foo() {
runBlocking(Dispatchers.Default) {
someSuspendMethod()
}
}

Thanks to https://proandroiddev.com/how-to-deadlock-your-android-app-with-runblocking-8dab02c2624d

#AndroidDev #Kotlin #Coroutines

Abhinav ⁉️
11 months ago

I wrote a #blog post about implementing a small interpreted #programming language with #coroutines: https://abhinavsarkar.net/posts/implementing-co-1/
#ProgrammingLanguages #plt #haskell

Bartek
11 months ago

Any recommendations for a smooth introduction to #Kotlin #Coroutines? Tutorials, books, webinars? Anything?

Colin Macleod
11 months ago

@notimetoplay Well, implementing #coroutines in a #programming language is non-trivial, you can't just push all your local state on a single stack anymore. But I agree that they are very nice to have. See this article for one of the benefits: https://www.magicsplat.com/blog/coro-iterate/ . Coroutines are also great for event-based code that would otherwise become a maze of callbacks.

Oliver
11 months ago

@rockthejvm did a Kotlin video! I could listen to Daniel forever. Even topics I already know about, but want to watch anyway to reinforce my understanding or maybe learn some new aspect, don't bore me out, because of his way of presenting. 👍🏻
Enjoy "#Kotlin #Coroutines and #StructuredConcurrency Tutorial, Part 1: Basics" on YouTube
https://youtu.be/Wpco6IK1hmY

Its a nice feeling when you are migrating from one software paradigm to another, and its a complete mess for a long time, and then you refactor something, and suddenly things are simple, clean, and just "Better".

I'm looking at you, #kotlin #coroutines in #android

Simon Vergauwen
1 year ago

Another #ArrowKt snippet today! Similarly to how #kotlin #Coroutines allows you to easily integrate with other concurrency frameworks through suspend.

Arrow will allow integration with other #functional data types 😍

Context receivers power this slick DSLs. Stable when? 🥲

droidcon
1 year ago

Watch talks from all our past #AndroidDev events 🎥 This week, we've got Lamberto Basti's talk from droidconLondon on how #Flow operators are made & how we can implement behaviours with a handful of lines by the power of #coroutines.

Full talk here: https://www.droidcon.com/2022/11/15/go-with-the-flow/

I like the simple and elegant syntax of #kotlin, the balance it strikes between #oop and functional styles, powerful concurrency model with #coroutines, all the while retaining full access to the rich library ecosystem of java.

tateisu​ :force:​:r_9a:
3 years ago

runBlocking{} のスコープからlaunchするときにDispatchersを省略するとすぐに開始しない。知らんかった… #Kotlin #Coroutines