Answer the question
In order to leave comments, you need to log in
How to process data from the database through multithreading in GO?
Hello comrades! Please help me figure it out.
The Golang application has a single threaded application. The application uses the GORM library from the database ( PostgreSQL ) to get a list of all products. Then it cycles through each one and, depending on the value of the status column , updates the value of the blocked column for the product .
var Tracker = func() {
var products []models.Products
// Получаем список продуктов из базы данных
if err := db.Find(&products).Error; err != nil {
log.Fatal(err)
return
}
// Парсим список продуктов
for i := 0; i < len(products); i++ {
product := models.Product{}
// В зависимости от статуса продукта выполнить разные действия.
if products[i].Status == 1 {
if err := db.Model(&product).Update("blocked", false).Error; err != nil {
log.Println(err)
return
}
} else if products[i].Status == 2 {
if err := db.Model(&product).Update("blocked", true).Error; err != nil {
log.Println(err)
return
}
}
}
}
var Tracker = func() {
var products []models.Products
// Получаем список продуктов из базы данных
if err := db.Find(&products).Error; err != nil {
log.Fatal(err)
return
}
for _, product := range products {
go Checker(product)
}
}
func Checker(product models.Product) {
if product.Status == 1 {
if err := db.Model(&product).Update("blocked", false).Error; err != nil {
log.Println(err)
return
}
} else if product.Status == 2 {
if err := db.Model(&product).Update("blocked", true).Error; err != nil {
log.Println(err)
return
}
}
}
Answer the question
In order to leave comments, you need to log in
In my opinion, this is all done in one query to the database: UPDATE products SET blocked = status == 2 WHERE status in (1,2)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question