M
M
Mamol272021-08-15 19:04:17
go
Mamol27, 2021-08-15 19:04:17

How to write to a channel without blocking golang?

Hello, I'm learning Go.
There are two goroutines, one writes to the channel (sender), the other reads this data (reader). However, the former writes more often than the latter reads. It is necessary that the sender can write the number to the channel, even if the reader has not yet read it, that is, update it, and the reader reads only fresh data.
At the same time, the sender does not work quite stably, for physical reasons, and does not guarantee that it will receive data to write to the channel for a known period of time.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
F
fops9311, 2021-08-16
@fops9311

Good afternoon.
As far as I understand, channels are not particularly suitable for such a task.
If, in the case of a new entry to the channel, the data becomes outdated, then it is better to use closures, for example:
func Entangle() (in func(interface{}), out func() interface{}) {
var data interface{}
var mu sync.Mutex
in = func(d interface{}) {
mu.Lock()
data = d
mu.Unlock()
}
out = func() interface{} {
mu.Lock()
d := data
mu.Unlock()
return d
}
return in, out
}
and using the returned function in - write, and with out - read.
You can also use a mutex to guarantee data integrity during concurrent reads and writes, also closed between these two functions, but this may sometimes not be necessary.

R
Roman Mirilaczvili, 2021-08-15
@2ord

Use (durable) message queues or a buffered channel (by specifying the length of the channel) capable of holding enough messages (eg 100) But if the program receives an interrupt signal, they will be lost. Therefore, the 1st option is more reliable.

and the reader read only fresh data.
If a send time attribute is sent in a message, the recipient can discard the message if it has become outdated.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question