79546138

Date: 2025-03-31 11:45:39
Score: 2.5
Natty:
Report link

Alright, so you're using an atomic version counter to make sure only the latest network request's result gets used. Each button click bumps up the version, and when the request finishes, it checks if its version is still the latest one. If not, it discards the result. Solid approach.

std::atomic<int> version{0};

// Button Click handler
void OnClick() {
    auto v = version.fetch_add(1, std::memory_order_acq_rel); // Increment version
    std::thread([v]() {
        int current = v + 1;
        auto r = network_request(current); // Perform network request
        if (version.compare_exchange_strong(current, current, std::memory_order_release, std::memory_order_relaxed)) {
            use_req(r); // Use the result if version matches
        }
    }).detach();
}

Why CAS and Not Just a Load?

You asked whether the CAS (compare_exchange_strong) could just be a load operation. Short answer: No. Here’s why:

What Happens When Multiple Clicks Happen?

Let's say you click the button twice:

  1. First click → version starts at 0, fetch_add makes it 1.

  2. Second click → version becomes 2.

  3. The first request finishes and checks if version is still 1. But nope, it's 2 now. So the first result is ignored.

  4. The second request finishes, sees that version is still 2, and its result gets used.

If we replaced CAS with just a load, we wouldn’t get this guarantee. The first request might read the version at 1 before fetch_add in the second click updates it, and it might wrongly think it should use its result.

Memory Order Considerations


TL;DR

Yes, CAS is necessary here. A plain load wouldn’t catch race conditions where the version changes between request start and completion. CAS ensures that only the result of the latest request gets used. Keep it as is. I spent quite some time on this answer as I desperately need that reputation to get the ability to comment on other's questions lol.

Reasons:
  • Blacklisted phrase (1): to comment
  • RegEx Blacklisted phrase (1.5): reputation
  • Long answer (-1):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • Low reputation (1):
Posted by: IneoSenigupta