까다로운 Golang 인터뷰 질문 - 부품 데이터 레이스

王林
풀어 주다: 2024-09-06 22:30:12
원래의
484명이 탐색했습니다.

Tricky Golang interview questions - Part Data Race

여기 또 다른 코드 리뷰 인터뷰 질문이 있습니다. 이 질문은 이전 질문보다 더 발전된 질문이며 더 높은 수준의 청중을 대상으로 합니다. 문제를 해결하려면 슬라이스에 대한 지식과 병렬 프로세스 간 데이터 공유가 필요합니다.

슬라이스 및 그 구성 방법에 익숙하지 않은 경우 슬라이스 헤더에 대한 이전 기사를 확인하세요

데이터 경쟁이란 무엇입니까?

데이터 경합은 두 개 이상의 스레드(Go의 경우 고루틴)가 동시에 공유 메모리에 액세스하고 이러한 액세스 중 적어도 하나가 쓰기 작업일 때 발생합니다. 액세스를 관리하기 위한 적절한 동기화 메커니즘(예: 잠금 또는 채널)이 없으면 데이터 손상, 일관되지 않은 상태 또는 충돌을 포함하여 예측할 수 없는 동작

이 발생할 수 있습니다.

본질적으로 데이터 경쟁은 다음과 같은 경우에 발생합니다.
  • 두 개 이상의 스레드(또는 고루틴)가 동시에
  • 동일한 메모리 위치에 액세스합니다.
  • 스레드(또는 고루틴) 중 적어도 하나가 해당 메모리에 쓰고
  • 있습니다.
  • 해당 메모리에 대한 액세스를 제어하는 ​​동기화
  • 가 없습니다.


이 때문에 스레드나 고루틴이 공유 메모리에 액세스하거나 수정하는 순서는 예측할 수 없으며 실행마다 다를 수 있는 비결정적 동작으로 이어집니다.

     +----------------------+      +---------------------+
     | Thread A: Write      |      | Thread B: Read      |
     +----------------------+      +---------------------+
     | 1. Reads x           |      | 1. Reads x          |
     | 2. Adds 1 to x       |      |                     |
     | 3. Writes new value  |      |                     |
     +----------------------+      +---------------------+

                    Shared variable x
                    (Concurrent access without synchronization)
로그인 후 복사

여기서 스레드 A는 x를 수정(쓰기)하고 동시에 스레드 B는 x를 읽고 있습니다. 두 스레드가 동시에 실행 중이고 동기화가 없으면 스레드 B는 스레드 A가 업데이트를 완료하기 전에 x를 읽을 수 있습니다. 결과적으로 데이터가 부정확하거나 일관성이 없을 수 있습니다.

질문: 팀원 중 한 명이 코드 검토를 위해 다음 코드를 제출했습니다. 코드를 주의 깊게 검토하고 잠재적인 문제를 식별하십시오.

검토해야 할 코드는 다음과 같습니다.

package main  

import (  
    "bufio"  
    "bytes"
    "io"
    "math/rand"
    "time"
)  

func genData() []byte {  
    r := rand.New(rand.NewSource(time.Now().Unix()))  
    buffer := make([]byte, 512)  
    if _, err := r.Read(buffer); err != nil {  
       return nil  
    }  
    return buffer  
}  

func publish(input []byte, output chan<- []byte) {  
    reader := bytes.NewReader(input)  

    bufferSize := 8  
    buffer := make([]byte, bufferSize)  

    for {  
       n, err := reader.Read(buffer)  
       if err != nil || err == io.EOF {  
          return  
       }  
       if n == 0 {  
          break  
       }  
       output <- buffer[:n]  
    }  
}  

func consume(input []byte) {  
    scanner := bufio.NewScanner(bytes.NewReader(input))  
    for scanner.Scan() {  
       b := scanner.Bytes()  
       _ = b  
       // does the magic  
    }  
}  

func main() {  
    data := genData()  
    workersCount := 4  
    chunkChannel := make(chan []byte, workersCount)  

    for i := 0; i < workersCount; i++ {  
       go func() {  
          for chunk := range chunkChannel {  
             consume(chunk)  
          }  
       }()  
    }  

    publish(data, chunkChannel)  
    close(chunkChannel)  
}
로그인 후 복사

여기에는 무엇이 있나요?

Publish() 함수는 입력 데이터를 청크 단위로 읽고 각 청크를 출력 채널로 보내는 역할을 합니다. 먼저 bytes.NewReader(input)를 사용하여 입력 데이터에서 판독기를 생성합니다. 이를 통해 데이터를 순차적으로 읽을 수 있습니다. 입력에서 읽는 동안 각 데이터 청크를 보관하기 위해 크기 8의 버퍼가 생성됩니다. 각 반복 동안 reader.Read(buffer)는 입력에서 최대 8바이트를 읽은 다음 함수는 최대 8바이트를 포함하는 이 버퍼(buffer[:n])의 조각을 출력 채널로 보냅니다. reader.Read(buffer)에 오류가 발생하거나 입력 데이터의 끝에 도달할 때까지 루프가 계속됩니다.

consumer() 함수는 채널에서 받은 데이터 청크를 처리합니다. bufio.Scanner를 사용하여 이러한 청크를 처리합니다. bufio.Scanner는 각 데이터 청크를 스캔하여 구성 방법에 따라 잠재적으로 라인이나 토큰으로 나눌 수 있습니다. 변수 b := scanner.Bytes()는 현재 스캔 중인 토큰을 검색합니다. 이 함수는 기본적인 입력 처리를 나타냅니다.

main()은 WorkersCount와 동일한 용량을 갖는 버퍼링된 채널 ChunkChannel을 생성하며 이 경우 4로 설정됩니다. 그런 다음 함수는 4개의 작업자 고루틴을 시작하며, 각각은 동시에 ChunkChannel에서 데이터를 읽습니다. 작업자는 데이터 청크를 수신할 때마다 Consumer() 함수를 호출하여 청크를 처리합니다. 게시() 함수는 생성된 데이터를 읽고 최대 8바이트의 청크로 나누어 채널로 보냅니다.

이 프로그램은 고루틴을 사용하여 여러 소비자를 생성하므로 동시 데이터 처리가 가능합니다. 각 소비자는 별도의 고루틴에서 실행되어 데이터 덩어리를 독립적으로 처리합니다.


이 코드를 실행하면 의심스러운 알림이 발생합니다.

[Running] go run "main.go"

[Done] exited with code=0 in 0.94 seconds
로그인 후 복사

하지만 문제가 있습니다. 데이터 경쟁 위험이 있습니다. 이 코드에서는 게시() 함수가 각 청크에 대해 동일한 버퍼 슬라이스를 재사용하기 때문에 잠재적인 데이터 경쟁이 있습니다. 소비자는 이 버퍼에서 동시에 읽고 있으며 슬라이스는 기본 메모리를 공유하므로 여러 소비자가 동일한 메모리를 읽을 수 있어 데이터 경쟁이 발생할 수 있습니다. 인종 감지 기능을 사용해 보겠습니다. Go는 데이터 경합을 감지하는 내장 도구인 경합 감지기
를 제공합니다. -race 플래그를 사용하여 프로그램을 실행하여 이를 활성화할 수 있습니다:

go run -race main.go
로그인 후 복사


실행 명령에 -race 플래그를 추가하면 다음과 같은 출력이 표시됩니다.

<🎜>
[Running] go run -race "main.go"

==================
WARNING: DATA RACE
Read at 0x00c00011e018 by goroutine 6:
  runtime.slicecopy()
      /GOROOT/go1.22.0/src/runtime/slice.go:325 +0x0
  bytes.(*Reader).Read()
      /GOROOT/go1.22.0/src/bytes/reader.go:44 +0xcc
  bufio.(*Scanner).Scan()
      /GOROOT/go1.22.0/src/bufio/scan.go:219 +0xef4
  main.consume()
      /GOPATH/example/main.go:40 +0x140
  main.main.func1()
      /GOPATH/example/main.go:55 +0x48

Previous write at 0x00c00011e018 by main goroutine:
  runtime.slicecopy()
      /GOROOT/go1.22.0/src/runtime/slice.go:325 +0x0
  bytes.(*Reader).Read()
      /GOROOT/go1.22.0/src/bytes/reader.go:44 +0x168
  main.publish()
      /GOPATH/example/main.go:27 +0xe4
  main.main()
      /GOPATH/example/main.go:60 +0xdc

Goroutine 6 (running) created at:
  main.main()
      /GOPATH/example/main.go:53 +0x50
==================
Found 1 data race(s)
exit status 66

[Done] exited with code=0 in 0.94 seconds
로그인 후 복사

The warning you’re seeing is a classic data race detected by Go’s race detector. The warning message indicates that two goroutines are accessing the same memory location (0x00c00011e018) concurrently. One goroutine is reading from this memory, while another goroutine is writing to it at the same time, without proper synchronization.

The first part of the warning tells us that Goroutine 6 (which is one of the worker goroutines in your program) is reading from the memory address 0x00c00011e018 during a call to bufio.Scanner.Scan() inside the consume() function.

Read at 0x00c00011e018 by goroutine 6:
  runtime.slicecopy()
  /GOROOT/go1.22.0/src/runtime/slice.go:325 +0x0
  bytes.(*Reader).Read()
  /GOROOT/go1.22.0/src/bytes/reader.go:44 +0xcc
  bufio.(*Scanner).Scan()
  /GOROOT/go1.22.0/src/bufio/scan.go:219 +0xef4
  main.consume()
  /GOPATH/example/main.go:40 +0x140
  main.main.func1()
  /GOPATH/example/main.go:55 +0x48
로그인 후 복사

The second part of the warning shows that the main goroutine previously wrote to the same memory location (0x00c00011e018) during a call to bytes.Reader.Read() inside the publish() function.

Previous write at 0x00c00011e018 by main goroutine:
  runtime.slicecopy()
  /GOROOT/go1.22.0/src/runtime/slice.go:325 +0x0
  bytes.(*Reader).Read()
  /GOROOT/go1.22.0/src/bytes/reader.go:44 +0x168
  main.publish()
  /GOPATH/example/main.go:27 +0xe4
  main.main()
  /GOPATH/example/main.go:60 +0xdc
로그인 후 복사

The final part of the warning explains that Goroutine 6 was created in the main function.

Goroutine 6 (running) created at:
  main.main()
  /GOPATH/example/main.go:53 +0x50
로그인 후 복사

In this case, while one goroutine (Goroutine 6) is reading from the buffer in consume(), the publish() function in the main goroutine is simultaneously writing to the same buffer, leading to the data race.

+-------------------+               +--------------------+
|     Publisher     |               |      Consumer      |
+-------------------+               +--------------------+
        |                                   |
        v                                   |
1. Read data into buffer                    |
        |                                   |
        v                                   |
2. Send slice of buffer to chunkChannel     |
        |                                   |
        v                                   |
 +----------------+                         |
 |  chunkChannel  |                         |
 +----------------+                         |
        |                                   |
        v                                   |
3. Consume reads from slice                 |
                                            v
                                    4. Concurrent access
                                    (Data Race occurs)
로그인 후 복사

Why the Data Race Occurs

The data race in this code arises because of how Go slices work and how memory is shared between goroutines when a slice is reused. To fully understand this, let’s break it down into two parts: the behavior of the buffer slice and the mechanics of how the race occurs. When you pass a slice like buffer[:n] to a function or channel, what you are really passing is the slice header which contains a reference to the slice’s underlying array. Any modifications to the slice or the underlying array will affect all other references to that slice.

buffer = [ a, b, c, d, e, f, g, h ]  <- Underlying array
           ↑
          Slice: buffer[:n]
로그인 후 복사
func publish(input []byte, output chan<- []byte) {  
    reader := bytes.NewReader(input)  

    bufferSize := 8  
    buffer := make([]byte, bufferSize)  

    for {  
       // ....
       output <- buffer[:n] // <-- passing is a reference to the underlying array
    }  
}
로그인 후 복사

If you send buffer[:n] to a channel, both the publish() function and any consumer goroutines will be accessing the same memory. During each iteration, the reader.Read(buffer) function reads up to 8 bytes from the input data into this buffer slice. After reading, the publisher sends buffer[:n] to the output channel, where n is the number of bytes read in the current iteration.

The problem here is that buffer is reused across iterations. Every time reader.Read() is called, it overwrites the data stored in buffer.

  • Iteration 1: publish() function reads the first 8 bytes into buffer and sends buffer[:n] (say, [a, b, c, d, e, f, g, h]) to the channel.
  • Iteration 2: The publish() function overwrites the buffer with the next 8 bytes, let’s say [i, j, k, l, m, n, o, p], and sends buffer[:n] again.

At this point, if one of the worker goroutines is still processing the first chunk, it is now reading stale or corrupted data because the buffer has been overwritten by the second chunk. Reusing a slice neans sharing the same memory.

How to fix the Data Race?

To avoid the race condition, we must ensure that each chunk of data sent to the channel has its own independent memory. This can be achieved by creating a new slice for each chunk and copying the data from the buffer to this new slice. The key fix is to copy the contents of the buffer into a new slice before sending it to the chunkChannel:

chunk := make([]byte, n)    // Step 1: Create a new slice with its own memory
copy(chunk, buffer[:n])     // Step 2: Copy data from buffer to the new slice
output <- chunk             // Step 3: Send the new chunk to the channel
로그인 후 복사

Why this fix works? By creating a new slice (chunk) for each iteration, you ensure that each chunk has its own memory. This prevents the consumers from reading from the buffer that the publisher is still modifying. copy() function copies the contents of the buffer into the newly allocated slice (chunk). This decouples the memory used by each chunk from the buffer. Now, when the publisher reads new data into the buffer, it doesn’t affect the chunks that have already been sent to the channel.

+-------------------------+           +------------------------+
|  Publisher (New Memory) |           | Consumers (Read Copy)  |
|  [ a, b, c ] --> chunk1 |           |  Reading: chunk1       |
|  [ d, e, f ] --> chunk2 |           |  Reading: chunk2       |
+-------------------------+           +------------------------+
         ↑                                    ↑
        (1)                                  (2)
   Publisher Creates New Chunk          Consumers Read Safely
로그인 후 복사

This solution works is that it breaks the connection between the publisher and the consumers by eliminating shared memory. Each consumer now works on its own copy of the data, which the publisher does not modify. Here’s how the modified publish() function looks:

func publish(input []byte, output chan<- []byte) {
    reader := bytes.NewReader(input)
    bufferSize := 8
    buffer := make([]byte, bufferSize)

    for {
        n, err := reader.Read(buffer)
        if err != nil || err == io.EOF {
            return
        }
        if n == 0 {
            break
        }

        // Create a new slice for each chunk and copy the data from the buffer
        chunk := make([]byte, n)
        copy(chunk, buffer[:n])

        // Send the newly created chunk to the channel
        output <- chunk
    }
}
로그인 후 복사

Summary

Slices Are Reference Types:
As mentioned earlier, Go slices are reference types, meaning they point to an underlying array. When you pass a slice to a channel or a function, you’re passing a reference to that array, not the data itself. This is why reusing a slice leads to a data race: multiple goroutines end up referencing and modifying the same memory.

Peruntukan Memori:
Apabila kita mencipta kepingan baharu dengan make([]bait, n), Go memperuntukkan blok memori yang berasingan untuk kepingan itu. Ini bermakna kepingan baharu (ketulan) mempunyai tatasusunan sandarannya sendiri, bebas daripada penimbal. Dengan menyalin data daripada penimbal[:n] ke dalam bongkah, kami memastikan setiap bongkah mempunyai ruang memori peribadinya sendiri.

Memori Penyahgandingan:
Dengan mengasingkan memori setiap bahagian daripada penimbal, penerbit boleh terus membaca data baharu ke dalam penimbal tanpa menjejaskan bahagian yang telah dihantar ke saluran. Setiap bahagian kini mempunyai salinan bebas datanya sendiri, jadi pengguna boleh memproses bahagian tersebut tanpa gangguan daripada penerbit.

Mencegah Perlumbaan Data:
Sumber utama perlumbaan data ialah akses serentak kepada penimbal yang dikongsi. Dengan mencipta kepingan baharu dan menyalin data, kami menghapuskan memori yang dikongsi, dan setiap goroutine beroperasi pada datanya sendiri. Ini menghapuskan kemungkinan keadaan perlumbaan kerana tiada lagi sebarang perbalahan mengenai ingatan yang sama.

Kesimpulan

Inti pembetulan adalah mudah tetapi berkuasa: dengan memastikan setiap bahagian data mempunyai ingatan sendiri, kami menghapuskan sumber kongsi (penampan) yang menyebabkan perlumbaan data. Ini dicapai dengan menyalin data daripada penimbal ke dalam kepingan baharu sebelum menghantarnya ke saluran. Dengan pendekatan ini, setiap pengguna menggunakan salinan datanya sendiri, bebas daripada tindakan penerbit, memastikan pemprosesan serentak yang selamat tanpa syarat perlumbaan. Kaedah penyahgandingan memori kongsi ini merupakan strategi asas dalam pengaturcaraan serentak. Ia menghalang tingkah laku yang tidak dapat diramalkan yang disebabkan oleh keadaan perlumbaan dan memastikan program Go anda kekal selamat, boleh diramal dan betul, walaupun apabila berbilang gorout mengakses data secara serentak.

Semudah itu!

위 내용은 까다로운 Golang 인터뷰 질문 - 부품 데이터 레이스의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!