Sobes.tech
Junior — Middle

Can a structure with two fields be considered safe for use in multithreaded conditions?

sobes.tech AI

Answer from AI

A struct with two fields in Go is not inherently thread-safe. Without additional synchronization, access to the struct's fields from multiple goroutines can lead to race conditions.

If the struct's fields do not change after initialization (i.e., the struct is immutable), then it is safe to read from multiple threads.

If the fields can change, then synchronization mechanisms such as sync.Mutex or sync.RWMutex should be used to ensure safety.

Example with mutex:

import "sync"

type SafeStruct struct {
    mu sync.Mutex
    field1 int
    field2 string
}

func (s *SafeStruct) Set(field1 int, field2 string) {
    s.mu.Lock()
    defer s.mu.Unlock()
    s.field1 = field1
    s.field2 = field2
}

func (s *SafeStruct) Get() (int, string) {
    s.mu.Lock()
    defer s.mu.Unlock()
    return s.field1, s.field2
}

Thus, the struct itself does not guarantee safety; it must be protected explicitly.

Can a structure with two fields be considered safe… - sobes.tech