C++ Atomic::fetch_and() 函式



C++ 的std::atomic::fetch_and()函式用於對原子物件的數值執行原子按位與操作。它透過使用給定引數進行按位與修改原子變數,確保執行緒安全,無需使用鎖。它返回操作前的原始值。

語法

以下是 std::atomic::fetch_and() 函式的語法。

T fetch_and (T val, memory_order sync = memory_order_seq_cst) volatile noexcept;
T fetch_and (T val, memory_order sync = memory_order_seq_cst) noexcept;

引數

  • val − 表示要應用的值。
  • sync − 表示操作的同步模式。

返回值

此函式返回呼叫前的包含值。

異常

此函式從不丟擲異常。

示例

在以下示例中,我們將考慮 fetch_and() 函式的基本用法。

#include <iostream>
#include <atomic>
int main()
{
    std::atomic<int> x(0b1100);
    int y = x.fetch_and(0b1010);
    std::cout << "Original value: " << y << std::endl;
    std::cout << "New value: " << x.load() << std::endl;
    return 0;
}

輸出

上述程式碼的輸出如下所示:

Original value: 12
New value: 8

示例

考慮以下示例,我們將使用多個 fetch_and() 並觀察輸出。

#include <iostream>
#include <atomic>
int main()
{
    std::atomic<int> x(0b00110);
    int a = x.fetch_and(0b10011);
    int b = x.fetch_and(0b10000);
    std::cout << "Result after first fetch_and: " << a << std::endl;
    std::cout << "Result after second fetch_and: " << b << std::endl;
    std::cout << "Final value: " << x.load() << std::endl;
    return 0;
}

輸出

如果我們執行上述程式碼,它將生成以下輸出:

Result after first fetch_and: 6
Result after second fetch_and: 2
Final value: 0

示例

讓我們看以下示例,我們將使用帶 std::memory_order_relaxed 的 fetch_and()。

#include <iostream>
#include <atomic>
#include <thread>
std::atomic<int> x(0b0101);
void a()
{
    int b = x.fetch_and(0b0100, std::memory_order_relaxed);
    std::cout << "Old value: " << b << ", New value: " << x.load() << '\n';
}
int main()
{
    std::thread t1(a);
    t1.join();
    return 0;
}

輸出

以下是上述程式碼的輸出:

Old value: 5, New value: 4
atomic.htm
廣告