찾다
백엔드 개발Golang까다로운 Golang 인터뷰 질문 - 부품 데이터 레이스

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

<p>



</p>여기에는 무엇이 있나요? <p>

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

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

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

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

<br>이 코드를 실행하면 의심스러운 알림이 발생합니다.</p>
<pre class="brush:php;toolbar:false">[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 ]  





<pre class="brush:php;toolbar:false">func publish(input []byte, output chan



<p>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. </p>

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

  • 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 



<p>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.<br>
</p>

<pre class="brush:php;toolbar:false">+-------------------------+           +------------------------+
|  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



<h3>
  
  
  Summary
</h3>

<p><strong>Slices Are Reference Types:</strong><br>
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.</p><p><strong>Peruntukan Memori:</strong><br>
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.</p>

<p><strong>Memori Penyahgandingan:</strong><br>
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.</p>

<p><strong>Mencegah Perlumbaan Data:</strong><br>
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.</p>

<h3>
  
  
  Kesimpulan
</h3>

<p>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.</p>

<p>Semudah itu!</p>


          

            
        

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

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
Golang in Action : 실제 예제 및 응용 프로그램Golang in Action : 실제 예제 및 응용 프로그램Apr 12, 2025 am 12:11 AM

Golang은 실제 응용 분야에서 탁월하며 단순성, 효율성 및 동시성으로 유명합니다. 1) 동시 프로그래밍은 Goroutines 및 채널을 통해 구현됩니다. 2) Flexible Code는 인터페이스 및 다형성을 사용하여 작성됩니다. 3) NET/HTTP 패키지로 네트워크 프로그래밍 단순화, 4) 효율적인 동시 크롤러 구축, 5) 도구 및 모범 사례를 통해 디버깅 및 최적화.

Golang : Go 프로그래밍 언어가 설명되었습니다Golang : Go 프로그래밍 언어가 설명되었습니다Apr 10, 2025 am 11:18 AM

GO의 핵심 기능에는 쓰레기 수집, 정적 연결 및 동시성 지원이 포함됩니다. 1. Go Language의 동시성 모델은 고루틴 및 채널을 통한 효율적인 동시 프로그래밍을 실현합니다. 2. 인터페이스 및 다형성은 인터페이스 방법을 통해 구현되므로 서로 다른 유형을 통일 된 방식으로 처리 할 수 ​​있습니다. 3. 기본 사용법은 기능 정의 및 호출의 효율성을 보여줍니다. 4. 고급 사용에서 슬라이스는 동적 크기 조정의 강력한 기능을 제공합니다. 5. 레이스 조건과 같은 일반적인 오류는 Getest-race를 통해 감지 및 해결할 수 있습니다. 6. 성능 최적화는 sync.pool을 통해 개체를 재사용하여 쓰레기 수집 압력을 줄입니다.

Golang의 목적 : 효율적이고 확장 가능한 시스템 구축Golang의 목적 : 효율적이고 확장 가능한 시스템 구축Apr 09, 2025 pm 05:17 PM

Go Language는 효율적이고 확장 가능한 시스템을 구축하는 데 잘 작동합니다. 장점은 다음과 같습니다. 1. 고성능 : 기계 코드로 컴파일, 빠른 달리기 속도; 2. 동시 프로그래밍 : 고어 라틴 및 채널을 통한 멀티 태스킹 단순화; 3. 단순성 : 간결한 구문, 학습 및 유지 보수 비용 절감; 4. 크로스 플랫폼 : 크로스 플랫폼 컴파일, 쉬운 배포를 지원합니다.

SQL 분류의 진술에 의한 순서 결과가 때때로 무작위로 보이는 이유는 무엇입니까?SQL 분류의 진술에 의한 순서 결과가 때때로 무작위로 보이는 이유는 무엇입니까?Apr 02, 2025 pm 05:24 PM

SQL 쿼리 결과의 정렬에 대해 혼란스러워합니다. SQL을 학습하는 과정에서 종종 혼란스러운 문제가 발생합니다. 최근 저자는 "Mick-SQL 기본 사항"을 읽고 있습니다.

기술 스택 컨버전스는 기술 스택 선택의 프로세스 일뿐입니까?기술 스택 컨버전스는 기술 스택 선택의 프로세스 일뿐입니까?Apr 02, 2025 pm 05:21 PM

기술 스택 컨버전스와 기술 선택의 관계, 소프트웨어 개발에서 기술 스택의 선택 및 관리는 매우 중요한 문제입니다. 최근에 일부 독자들은 ...

반사 비교를 사용하고 GO의 세 구조의 차이점을 처리하는 방법은 무엇입니까?반사 비교를 사용하고 GO의 세 구조의 차이점을 처리하는 방법은 무엇입니까?Apr 02, 2025 pm 05:15 PM

GO 언어로 세 가지 구조를 비교하고 처리하는 방법. GO 프로그래밍에서는 때때로 두 구조의 차이점을 비교하고 이러한 차이점을 ...에 적용해야합니다.

GO에서 전 세계적으로 설치된 패키지를 보는 방법?GO에서 전 세계적으로 설치된 패키지를 보는 방법?Apr 02, 2025 pm 05:12 PM

GO에서 전 세계적으로 설치된 패키지를 보는 방법? Go Language로 발전하는 과정에서 Go는 종종 사용합니다 ...

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

Dreamweaver Mac版

Dreamweaver Mac版

시각적 웹 개발 도구

맨티스BT

맨티스BT

Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

VSCode Windows 64비트 다운로드

VSCode Windows 64비트 다운로드

Microsoft에서 출시한 강력한 무료 IDE 편집기

PhpStorm 맥 버전

PhpStorm 맥 버전

최신(2018.2.1) 전문 PHP 통합 개발 도구