N
N
nurzhannogerbek2019-03-29 10:30:30
go
nurzhannogerbek, 2019-03-29 10:30:30

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
      }
    }
  }
}

I'm trying to transfer this single-threaded logic to multithreading. To what extent is my following code correct in your opinion, and what are the bottlenecks here? How else can you optimize the processing speed?
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

1 answer(s)
S
Sergey Tikhonov, 2019-03-29
@nurzhannogerbek

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 question

Ask a Question

731 491 924 answers to any question