C++ Atomic::operator--() 函式。



C++ 的std::atomic::operator--() 函式用於對原子變數執行原子遞減操作。這確保了遞減操作以原子方式執行,這意味著它是執行緒安全的並且沒有競爭條件。

operator--() 函式可以在前置遞減和後置遞減中使用。

語法

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

T operator--() volatile noexcept;
T operator--() noexcept;
or	
T operator-- (int) volatile noexcept;
T operator-- (int) noexcept;

引數

它不接受任何引數。

返回值

它返回修改前原子變數的值。

異常

此函式從不丟擲異常。

示例

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

#include <iostream>
#include <atomic>
int main()
{
    std::atomic<int> x(8);
    --x;
    std::cout << "Result : " << x.load() << std::endl;
    return 0;
}

輸出

以上程式碼的輸出如下:

Result : 7

示例

考慮以下示例,我們將在此示例中在迴圈中使用遞減。

#include <iostream>
#include <atomic>
int main()
{
    std::atomic<int> x(4);
    for (int i = 0; i < 3; ++i) {
        --x;
    }
    std::cout << "Result : " << x.load() << std::endl;
    return 0;
}

輸出

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

Result : 1

示例

讓我們看下面的例子,我們將在這裡在多執行緒環境中使用遞減。

#include <iostream>
#include <atomic>
#include <thread>
#include <vector>
void a(std::atomic<int>& b)
{
    --b;
}
int main()
{
    std::atomic<int> x(20);
    std::vector<std::thread> x1;
    for (int y = 0; y < 13; ++y) {
        x1.push_back(std::thread(a, std::ref(x)));
    }
    for (auto& t : x1) {
        t.join();
    }
    std::cout << "Result : " << x.load() << std::endl;
    return 0;
}

輸出

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

Result : 7
atomic.htm
廣告