Blacksad
Blacksad

Reputation: 15422

Go-style channels in C

For a real time DSP program in C, I need something like Go-style channels to communicate between threads:

I was wondering if using good old streams was a good idea, or not. If not, is there a good practice and/or a library to get something as close as Go channels as possible?

Upvotes: 5

Views: 2534

Answers (2)

Marcus Müller
Marcus Müller

Reputation: 36352

What you're describing describes a thread-safe queue.

The Apache Project has one implementation. GLib has another implementation.

Other than that, a lot of users have actually shared their pthread queue implementations, assuming that was what you're using.

Upvotes: 1

Rochus
Rochus

Reputation: 69

Go supports both buffered and unbuffered channels; unbuffered channels actually correspond to a "rendezvous" between two threads, which allows the threads to directly exchange data, i.e. without requiring an additional buffer; thread rendezvous can be implemented e.g. with a barrier (see e.g. https://en.wikipedia.org/wiki/Barrier_(computer_science)). Your small, fixed-size tokens seem well suited for the unbuffered approach.

Buffered channels in contrast can be implemented as thread-safe queues, as already mentioned. In FreeRTOS you can e.g. use xQueueCreate to create such a queue.

I recently implemented a C library which supports the semantics of buffered as well as unbuffered Go channels based on Pthreads (see https://github.com/rochus-keller/CspChan). You didn't provide information about your implementation environment. Porting the library to FreeRTOS (or similar low-level operating systems) looks feasible though.

Upvotes: 0

Related Questions