Skip to content

Commit

Permalink
Invoke handlers from their own Goroutines
Browse files Browse the repository at this point in the history
  • Loading branch information
stv0g committed May 15, 2023
1 parent 4697f51 commit 898746c
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 35 deletions.
8 changes: 7 additions & 1 deletion agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -358,7 +358,13 @@ func NewAgent(config *AgentConfig) (*Agent, error) { //nolint:gocognit
}

go a.taskLoop()
a.startOnConnectionStateChangeRoutine()

// CandidatePair and ConnectionState are usually changed at once.
// Blocking one by the other one causes deadlock.
// Hence, we call handlers from independent Goroutines.
go a.candidatePairRoutine()
go a.connectionStateRoutine()
go a.candidateRoutine()

// Restart is also used to initialize the agent for the first time
if err := a.Restart(config.LocalUfrag, config.LocalPwd); err != nil {
Expand Down
49 changes: 15 additions & 34 deletions agent_handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,39 +41,20 @@ func (a *Agent) onConnectionStateChange(s ConnectionState) {
}
}

func (a *Agent) startOnConnectionStateChangeRoutine() {
go func() {
for {
// CandidatePair and ConnectionState are usually changed at once.
// Blocking one by the other one causes deadlock.
p, isOpen := <-a.chanCandidatePair
if !isOpen {
return
}
a.onSelectedCandidatePairChange(p)
}
}()
go func() {
for {
select {
case s, isOpen := <-a.chanState:
if !isOpen {
for c := range a.chanCandidate {
a.onCandidate(c)
}
return
}
go a.onConnectionStateChange(s)
func (a *Agent) candidatePairRoutine() {
for p := range a.chanCandidatePair {
a.onSelectedCandidatePairChange(p)
}
}

func (a *Agent) connectionStateRoutine() {
for s := range a.chanState {
go a.onConnectionStateChange(s)
}
}

case c, isOpen := <-a.chanCandidate:
if !isOpen {
for s := range a.chanState {
go a.onConnectionStateChange(s)
}
return
}
a.onCandidate(c)
}
}
}()
func (a *Agent) candidateRoutine() {
for c := range a.chanCandidate {
a.onCandidate(c)
}
}

0 comments on commit 898746c

Please sign in to comment.