我试图遍历一个数组并复制数组中的每个值。我想在一个单独的goroutine中旋转每个循环。当我使用goroutines运行它时,它会比数组的大小(len(Array)-1)小一号,但是如果我摆脱了goroutine,它就可以正常工作。
我是否缺少有关该如何工作的信息?运行goroutine时总是总是少一个,这似乎很奇怪。下面是我的代码。
func createEventsForEachWorkoutReference(plan *sharedstructs.Plan, user *sharedstructs.User, startTime time.Time, timeZoneKey *string, transactionID *string, monitoringChannel chan interface{}) {
//Set the activity type as these workouts are coming from plans
activityType := "workout"
for _, workoutReference := range plan.WorkoutReferences {
go func(workoutReference sharedstructs.WorkoutReference) {
workout, getWorkoutError := workout.GetWorkoutByName(workoutReference.WorkoutID.ID, *transactionID)
if getWorkoutError == nil && workout != nil {
//For each workout, create a reference to be inserted into the event
reference := sharedstructs.Reference{ID: workout.WorkoutID, Type: activityType, Index: 0}
referenceArray := make([]sharedstructs.Reference, 0)
referenceArray = append(referenceArray, reference)
event := sharedstructs.Event{
EventID: uuidhelper.GenerateUUID(),
Description: workout.Description,
Type: activityType,
UserID: user.UserID,
IsPublic: false,
References: referenceArray,
EventDateTime: startTime,
PlanID: plan.PlanID}
//Insert the Event into the databse, I don't handle errors intentionally as it will be async
creationError := eventdomain.CreateNewEvent(&event, transactionID)
if creationError != nil {
redFalconLogger.LogCritical("plan.createEventsForEachWorkoutReference() Error Creating a workout"+creationError.Error(), *transactionID)
}
//add to the outputchannel
monitoringChannel <- event
//Calculate the next start time for the next loop
startTime = calculateNextEventTime(&startTime, &workoutReference.RestTime, timeZoneKey, transactionID)
}
}(workoutReference)
}
return
}
更深入的研究之后,我认为我已经找到了根本原因,但还没有找到(优雅的)解决方案。
似乎正在发生的事情是,我的调用函数也正在异步goroutine中运行,并使用“ chan interface {}”来监视进度并将其流回客户端。在数组的最后一项上,它正在完成调用goroutine,然后才能对chan进行处理。
等待频道处理完成的正确方法是什么?以下是我用来提供上下文的单元测试的一部分。
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
createEventsForEachWorkoutReference(plan, &returnedUser, startDate, &timeZone, &transactionID, monitoringChan)
}()
var userEventArrayList []sharedstructs.Event
go func() {
for result := range monitoringChan {
switch result.(type) {
case sharedstructs.Event:
counter++
event := result.(sharedstructs.Event)
userEventArrayList = append(userEventArrayList, event)
fmt.Println("Channel Picked Up New Event: " + event.EventID + " with counter " + strconv.Itoa(counter))
default:
fmt.Println("No Match")
}
}
}()
wg.Wait()
//I COULD SLEEP HERE BUT THAT SEEMS HACKY
close(monitoringChan)
想再添加一个示例(没有我的自定义代码)。您可以注释掉睡眠行以查看它是否可以在那里工作。
答案 0 :(得分:0)
终于找到答案了……
问题是我需要在第一个goroutine中关闭我的MonitoringChan,然后在第二个goroutine中监视(Defer wg.close())。当我这样做的时候效果很好!