goroutines | provides utilities to perform common tasks on goroutines
kandi X-RAY | goroutines Summary
kandi X-RAY | goroutines Summary
This package provides utilities to perform common tasks on goroutines - waiting for a goroutine to start, timeouts, do somethting before or after a goroutine function inside the same goroutine and recover from panic. It has a simple fluent API (see tests).
Support
Quality
Security
License
Reuse
Top functions reviewed by kandi - BETA
- Timeout sets the timeout .
- New returns a new Go struct .
goroutines Key Features
goroutines Examples and Code Snippets
Community Discussions
Trending Discussions on goroutines
QUESTION
I'm trying to understand best practices for Golang concurrency. I read O'Reilly's book on Go's concurrency and then came back to the Golang Codewalks, specifically this example:
https://golang.org/doc/codewalk/sharemem/
This is the code I was hoping to review with you in order to learn a little bit more about Go. My first impression is that this code is breaking some best practices. This is of course my (very) unexperienced opinion and I wanted to discuss and gain some insight on the process. This isn't about who's right or wrong, please be nice, I just want to share my views and get some feedback on them. Maybe this discussion will help other people see why I'm wrong and teach them something.
I'm fully aware that the purpose of this code is to teach beginners, not to be perfect code.
Issue 1 - No Goroutine cleanup logic
...ANSWER
Answered 2021-Jun-15 at 02:48It is the
main
method, so there is no need to cleanup. Whenmain
returns, the program exits. If this wasn't themain
, then you would be correct.There is no best practice that fits all use cases. The code you show here is a very common pattern. The function creates a goroutine, and returns a channel so that others can communicate with that goroutine. There is no rule that governs how channels must be created. There is no way to terminate that goroutine though. One use case this pattern fits well is reading a large resultset from a database. The channel allows streaming data as it is read from the database. In that case usually there are other means of terminating the goroutine though, like passing a context.
Again, there are no hard rules on how channels should be created/closed. A channel can be left open, and it will be garbage collected when it is no longer used. If the use case demands so, the channel can be left open indefinitely, and the scenario you worry about will never happen.
QUESTION
Is there a proven programmatic way to achieve mutual exclusion of multiple Mutexes / Locks / whatever in Golang? Eg.
...ANSWER
Answered 2021-Jun-11 at 09:51So is there any way to acquire those locks only if all of them are available?
No. Not with standard library mutex at least. There is no way to "check" if a lock is available, or "try" acquiring a lock. Every call of Lock()
will block until locking is successful.
The implementation of mutex relies on atomic operations which only act on a single value at once. In order to achieve what you describe, you'd need some kind of "meta locking" where execution of the lock and unlock methods are themselves protected by a lock, but this probably isn't necessary just to have correct and safe locking in your program:
Penelope Stevens' comment explains correctly: As long as the order of acquisition is consistent between different goroutines, you won't get deadlocks, even for arbitrary subsets of the locks, if each goroutine eventually releases the locks it acquires.
If the structure of your program provides some obvious locking order, then use that. If not, you can create your own special mutex type that has intrinsic ordering.
QUESTION
Following is the code:
...ANSWER
Answered 2021-Jun-09 at 11:09Looking at your code, two things can cause a deadlock:
errg.Wait()
blocks the execution of the main goroutine until all initialized goroutines are finished. However, each goroutine is blocked when trying to write tomapChan
, because you never get to read from it (because it is below theerrg.Wait()
).- You never read from
sliceChan
, so that is a potential deadlock right there.
Here is the link to the modified Playground code, but most of the changes are in the main
function.
QUESTION
I have a goroutine inside a loop and the way I am handling the error is that I add it to a channel and after all the goroutines are finished, I check if there was an error and I return accordingly.
The issue with this is that I want to return an error as soon as I get it so that I don't spend time waiting for all the goroutines to finish as it would be inefficient.
I tried adding the select
statement but it doesn't work and I can't add the select
statement inside the goroutines since I want to exit the for loop and the try
function too.
How can I do this?
Here is the code:
...ANSWER
Answered 2021-Jun-08 at 16:44I have found tomb to be useful for this. Below is a stripped-down non-working example that shows the gist, without handling things like variable encapsulation in the loop. It should give you the idea, but I'm happy to clarify on any points.
QUESTION
How to manage MongoDB connection for more than 100000 goroutines in golang.
I have created one *mongo.Client
instance then using this same client but it creates multiple connections.
ANSWER
Answered 2021-Jun-06 at 21:11The mongo.Client
manages an internal connection pool. You do not have to worry about that. mongo.Client
is safe for concurrent use.
If you want to limit the internal pool, you may do so at connection using ClientOptions
. For example:
QUESTION
Sry this title might be misleading. Actually the full code is here below:
...ANSWER
Answered 2021-May-28 at 08:22With the wg
waitgroup (as coded in your current group) : when the subscribe
function returns, you know that the waiting goroutine has at least started its execution.
So when your main function reaches button.Clicked.Broadcast()
, there's a good chance the two goroutines are actually waiting on their button.Clicked.Wait()
call.
Without the wg
, you have no guarantee that the goroutines have even started, and your code may call button.Clicked.Broadcast()
too soon.
Note that your use of wg
merely makes it less probable for the deadlock to happen, but it won't prevent it in all cases.
Try compiling your binary with -race
, and run it in a loop (e.g from bash : for i in {1..100}; do ./myprogram; done
), I think you will see that the same problem happens sometimes.
QUESTION
In a project the program receives data via websocket. This data needs to be processed by n algorithms. The amount of algorithms can change dynamically.
My attempt is to create some pub/sub pattern where subscriptions can be started and canceled on the fly. Turns out that this is a bit more challenging than expected.
Here's what I came up with (which is based on https://eli.thegreenplace.net/2020/pubsub-using-channels-in-go/):
...ANSWER
Answered 2021-May-27 at 13:32Before diving into your solution and its issues, let me recommend again another Broker approach presented in this answer: How to broadcast message using channel
Now on to your solution.
Whenever you launch a goroutine, always think of how it will end and make sure it does if the goroutine is not ought to run for the lifetime of your app.
QUESTION
TL;DR I want to have the functionality where a channel has two extra fields that tell the producer whether it is allowed to send to the channel and if so tell the producer what value the consumer expects. Although I know how to do it with shared memory, I believe that this approach goes against Go's ideology of "Do not communicate by sharing memory; instead, share memory by communicating."
Context:
I wish to have a server S that runs (besides others) three goroutines:
- Listener that just receives UDP packets and sends them to the demultplexer.
- Demultiplexer that takes network packets and based on some data sends it into one of several channels
- Processing task which listens to one specific channel and processes data received on that channel.
To check whether some devices on the network are still alive, the processing task will periodically send out nonces over the network and then wait for k seconds. In those k seconds, other participants of my protocol that received the nonce will send a reply containing (besides other information) the nonce. The demultiplexer will receive the packets from the listener, parse them and send them to the processing_channel
. After the k seconds elapsed, the processing task processes the messages pushed onto the processing_channel
by the demultiplexer.
I want the demultiplexer to not just blindly send any response (of the correct type) it received onto the the processing_channel
, but to instead check whether the processing task is currently even expecting any messages and if so which nonce value it expects. I made this design decision in order to drop unwanted packets a soon as possible.
My approach:
In other languages, I would have a class with the following fields (in pseudocode):
...ANSWER
Answered 2021-May-22 at 17:31Yes, the approach described by you doesn't align with Golang's Idiomatic way of implementation. And you have rightly pointed out that in the above approach you are communicating by sharing memory.
To achieve this in Go's Idiomatic way, one of the approaches could be that your Demultiplexer
"remembers" all the processing_channels
that are expecting nonce and the corresponding type of the nonce. Whenever a processing_channels
is ready to receive a reply, it sends a signal to the Demultiplexe
saying that it is expecting a reply.
Since Demultiplexer
is at the center of all the communication it can maintain a mapping between a processing_channel
& the corresponding nonce it expects. It can also maintain a "registry" of all the processing_channels
which are expecting a reply.
In this approach, we are Sharing memory by communicating
For communicating that a processing_channel
is expecting a reply, the following struct
can be used:
QUESTION
Sending data to integer channel in slice of channels is resulting into deadlock
The code is expected to create 5 (+1 fanInChan
) channels. These channels are used for send integer values through send()
and receive the same in receive()
and finally Fan-in the them to fanInChan
.
Code:-
...ANSWER
Answered 2021-May-21 at 12:45The statement channels := make([]chan int, 5)
is allocating a array with nil channels which
- Blocks receiving
<- channel
from channel - Blocks sending
channel <- value
into channel - panics on closing
close(channel)
So you have to initialize each channel individually to recive integer values.
You should init the channels in the channels
array before using those.
QUESTION
I just don't understand why ctx.Done() is not being executed even though I am passing context and calling the cancel from the main? What am I doing wrong here?
...ANSWER
Answered 2021-May-19 at 17:56The goroutine executes the default branch twice and blocks on send to c
. The <-ctx.Done()
case is not executed because the goroutine is stuck in the default branch.
Fix the problem by sending from the select case instead of the branch statements.
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
Vulnerabilities
No vulnerabilities reported
Install goroutines
Support
Reuse Trending Solutions
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
Find more librariesStay Updated
Subscribe to our newsletter for trending solutions and developer bootcamps
Share this Page