Sync Primitives Questions with Answers

9 practice questions on Sync Primitives (Go) with answers and step-by-step solutions. Try 9 samples below, then practise all 9 free in the AptiNest app.

Sample questions

Question 1Easy

What is context.Context mainly used for?

  1. Logging
  2. Storing global configuration that every package reads at startup instead of using flags
  3. Replacing channels
  4. Carrying cancellation, deadlines and request-scoped values across calls

Answer: D. Carrying cancellation, deadlines and request-scoped values across calls

Explanation

Functions check ctx.Done() to stop work when the caller cancels or a deadline passes.

Step-by-step solution

  1. Context is used to carry cancellation signals across function calls.
  2. It also holds deadlines for operations to time out properly.
  3. Request-scoped values are passed through context for efficient access.
  4. Functions use ctx.Done() to detect when cancellation happens.
  5. This helps stop ongoing work gracefully without errors.
  6. Final answer: Carrying cancellation, deadlines and request-scoped values across calls.

Why the other options are wrong

  • A. Logging is done with the log package or a logging library; context is not for that.
  • B. Global configuration is not context's job; config is read from flags, files or env.
  • C. Context does not replace channels; it signals cancellation, while channels pass data.

Tip: Use context for managing cancellation and deadlines in Go programs.

Question 2Easy

By convention, which parameter position does context.Context take in Go functions?

  1. The first parameter, usually named ctx
  2. The last parameter
  3. Inside a struct field, so it is stored once and shared by every method of the type
  4. It is never passed explicitly

Answer: A. The first parameter, usually named ctx

Explanation

func Fetch(ctx context.Context, id string) is the standard form.

Step-by-step solution

  1. In Go, functions use context.Context to manage cancellation and deadlines.
  2. The context is passed as the first parameter in function signatures.
  3. This convention helps developers easily identify and handle context in their code.
  4. Functions like Fetch take context.Context as the first parameter, usually named ctx.
  5. So the correct position for context.Context is the first parameter.

Why the other options are wrong

  • B. The last parameter is not the convention; ctx comes first, so this is not idiomatic.
  • C. A context is not stored in structs by convention; it is passed explicitly to each call.
  • D. Context is passed explicitly in calls; leaving it out is not the convention.

Tip: Remember: context.Context is always the first parameter in Go functions.

Question 3Easy

What does sync.Mutex provide?

  1. A buffered channel that queues goroutines and wakes them one by one in arrival order
  2. A way to start goroutines
  3. Mutual exclusion: one goroutine at a time in a critical section
  4. Atomic integer types

Answer: C. Mutual exclusion: one goroutine at a time in a critical section

Explanation

Lock and Unlock around shared data; defer mu.Unlock() is a common pattern.

Step-by-step solution

  1. sync.Mutex ensures only one goroutine can access shared data at a time.
  2. It uses Lock and Unlock methods to control access to critical sections.
  3. Defer mu.Unlock() is used to release the lock after use.
  4. This prevents race conditions by enforcing mutual exclusion.
  5. Final answer: Mutual exclusion: one goroutine at a time in a critical section.

Why the other options are wrong

  • A. A buffered channel is not sync.Mutex; a mutex locks a section rather than queuing work.
  • B. Starting goroutines is done with the go keyword, not with sync.Mutex.
  • D. Atomic integer types live in sync/atomic, not in sync.Mutex.

Question 4Medium

Why might sync/atomic be preferred over a mutex for a simple counter?

  1. It allows non-integer values only
  2. It updates the value atomically without a lock, with less overhead
  3. It makes the counter persistent
  4. Mutexes cannot protect integer variables, so counters must always use the atomic package

Answer: B. It updates the value atomically without a lock, with less overhead

Explanation

atomic.AddInt64 or atomic.Int64 suits single-value updates; mutexes suit multi-step critical sections.

Step-by-step solution

  1. A mutex locks and unlocks around the counter.
  2. atomic uses a single CPU instruction.
  3. So it avoids lock overhead and contention.

Why the other options are wrong

  • A. Atomics work on integers and pointers, not 'non-integers only'.
  • C. Atomics do not persist anything.
  • D. Mutexes can protect any variable.

Question 5Medium

What is the output?

package main

import (
	"context"
	"fmt"
)

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	cancel()
	<-ctx.Done()
	fmt.Println(ctx.Err())
}
  1. context canceled
  2. Deadlock: all goroutines are asleep
  3. <nil>
  4. context deadline exceeded

Answer: A. context canceled

Explanation

After cancel, Done is closed and Err returns context.Canceled, which prints as 'context canceled'.

Step-by-step solution

  1. cancel() closes ctx.Done()
  2. ctx.Err() reads the error.
  3. fmt.Println outputs 'context canceled'
  4. The program exits normally.
  5. Final answer: context canceled.

Why the other options are wrong

  • B. No deadlock: cancel closes Done already, so the receive returns at once.
  • C. Err is not nil after cancel; it holds context canceled, so <nil> is wrong here.
  • D. No deadline was set, so the error is not deadline exceeded; the cancel call caused it.

Tip: Remember cancel() closes the Done channel.

Question 6Medium

What is the output?

package main

import (
	"fmt"
	"sync"
)

func main() {
	var once sync.Once
	count := 0
	for i := 0; i < 3; i++ {
		once.Do(func() { count++ })
	}
	fmt.Println(count)
}
  1. 1
  2. 3
  3. 0
  4. Compile error

Answer: A. 1

Explanation

sync.Once runs the function only on the first Do call, which is useful for lazy initialisation.

Step-by-step solution

  1. sync.Once ensures the function runs only once, even if called multiple times.
  2. The loop runs 3 times but the func inside once.Do runs only once, incrementing count by 1.
  3. Count starts at 0 and is incremented once, so final value is 1.
  4. fmt.Println prints the final value of count, which is 1.
  5. Final answer: 1.

Why the other options are wrong

  • B. The Do call runs its function only once, so count is not incremented three times.
  • C. count starts at 0 and Do runs the increment once, so 0 is wrong.
  • D. No compile error: sync.Once and the closure are valid, so the program builds and runs.

Tip: Remember sync.Once executes its function only on the first call.

Question 7Medium

sync.RWMutex is useful when:

  1. You need to send values between goroutines
  2. Reads are frequent and writes rare, since readers can share the lock
  3. You want a lock that can be unlocked twice
  4. Writes greatly outnumber reads, since writers can share the lock while readers wait

Answer: B. Reads are frequent and writes rare, since readers can share the lock

Explanation

Many readers may hold RLock together; a writer's Lock is exclusive.

Step-by-step solution

  1. sync.RWMutex lets many readers hold the lock at the same time.
  2. A writer needs exclusive access, so it waits for readers to finish.
  3. So it helps when reads are frequent and writes are rare, which is option B.

Why the other options are wrong

  • A. Sending values between goroutines is the job of channels, not a mutex.
  • C. A mutex cannot be unlocked twice; unlocking an unlocked mutex is a fatal error that crashes the program and cannot be recovered.
  • D. Writers do not share the lock; readers share it, so it helps when reads dominate.

Tip: RWMutex: many readers at once, one writer at a time.

Question 8Hard

Why must a sync.Mutex not be copied after first use?

  1. Copying a mutex is a compile error, so the program will not build until the copy is removed
  2. Mutexes are pointers already
  3. The copy duplicates its internal state, breaking mutual exclusion
  4. Copies are automatically shared

Answer: C. The copy duplicates its internal state, breaking mutual exclusion

Explanation

Pass structs containing mutexes by pointer; go vet's copylocks check catches this.

Step-by-step solution

  1. Sync.Mutex uses internal state to track locks.
  2. Copying it duplicates this state, leading to incorrect locking behavior.
  3. This breaks mutual exclusion, allowing multiple locks on the same resource.
  4. The copy creates a new mutex with its own state, not shared with the original.
  5. Final answer: The copy duplicates its internal state, breaking mutual exclusion.

Why the other options are wrong

  • A. Copying a mutex is not a compile error; it builds, but the copy misbehaves at run time.
  • B. Mutexes are not pointers; sync.Mutex is a struct value, so copying it copies its state.
  • D. Copies are not shared automatically; a copy gets its own separate state, not the original's.

Tip: Never copy a Mutex after first use; pass by pointer instead.

Question 9Hard

A deadlock occurs when goroutine A holds lock 1 and waits for lock 2, while B holds 2 and waits for 1. A standard prevention is:

  1. Use RWMutex everywhere instead of Mutex, because read-write locks cannot deadlock
  2. Call runtime.GC() before locking
  3. Always acquire locks in the same global order
  4. Use more goroutines

Answer: C. Always acquire locks in the same global order

Explanation

Consistent lock ordering removes the circular wait.

Step-by-step solution

  1. Deadlock happens when two goroutines wait for each other's locks.
  2. Acquiring locks in a fixed global order avoids this cycle.
  3. Locks acquired in same order prevent circular dependency.
  4. This ensures no deadlock occurs between goroutines.
  5. Final answer: Always acquire locks in the same global order.

Why the other options are wrong

  • A. RWMutex does not prevent lock-order cycles; it can still deadlock.
  • B. runtime.GC does not release locks or fix lock ordering, so the cycle stays.
  • D. More goroutines do not fix lock ordering; they add contention and cannot break the cycle.

Tip: Always lock in a fixed order to avoid deadlocks.

Practise all 9 questions free

The full question bank with timed practice, progress tracking and Vidya, your AI tutor. Free, no ads.

Open this topic in the app →

Related topics

See all Go topics · All topics