cppadvanced15 minutes

Refactor a Complex C++ Matrix Multiplication with Thread Safety and Performance in Mind

Improve a messy and inefficient C++ matrix multiplication code by refactoring it to enhance readability, performance, and thread safety while preserving its original functionality.

Challenge prompt

You are provided with a C++ function that multiplies two matrices in a nested loop structure. The code is functional but suffers from poor readability, redundant computations, and lacks thread safety for concurrent matrix multiplication tasks. Refactor this function to improve its code quality by applying appropriate C++ best practices for readability, performance optimization (such as reducing unnecessary operations), and ensure that the multiplication can safely run in multithreaded contexts. Do not change the core logic or output of the function. Your refactoring should include: - Clear variable naming and organization - Avoid redundant computations or memory usage - Use const correctness as appropriate - Make the function safely callable in parallel from multiple threads You can assume the input matrices are valid (non-empty and rectangular) and use standard containers or pointers as you prefer, but clarify your choice in comments.

Guidance

  • Identify and eliminate redundant variable assignments and computations inside loops.
  • Use const references or pointers for input parameters where mutation is not needed.
  • Avoid shared mutable state or use local variables only to enable thread safety.
  • Consider using standard library containers (like std::vector) with size information passed explicitly.

Hints

  • Check if any variable is unnecessarily being assigned inside inner loops multiple times.
  • Mark input matrices as const references to prevent accidental mutation.
  • Avoid static or global variables that could cause race conditions when used in concurrent environments.

Starter code

void multiplyMatrices(const int* A, int rowsA, int colsA, const int* B, int rowsB, int colsB, int* result) {
    for (int i = 0; i < rowsA; ++i) {
        for (int j = 0; j < colsB; ++j) {
            int sum = 0;
            for (int k = 0; k < colsA; ++k) {
                int a_val = A[i * colsA + k];
                int b_val = B[k * colsB + j];
                sum += a_val * b_val;
            }
            result[i * colsB + j] = sum;
        }
    }
}

Expected output

No change in matrix multiplication result for any valid inputs; the refactored function produces the same output as the original but with cleaner, safer, and more efficient code.

Core concepts

C++ refactoringperformance optimizationthread safetyconst correctness

Challenge a Friend

Send this duel to someone else and see if they can solve it.