C++11多线程同步方法

std::mutex

#include 
#include 
#include 
#include 

using namespace std;

volatile int counter = 0;

void ft1()
{
    for (int i = 0; i < 100000; ++i)
    {
        ++counter;
    }
}

int main()
{
    std::vector ts;
    for(int i = 0; i < 5; ++i)
    {
        ts.emplace_back(std::thread(ft1));
    }

    for (auto& t : ts)
    {
        t.join();
    }

    cout << counter << endl;
    system("pause");
    return 0;
}

输出结果: counter 小于 5 * 100000

#include 
#include 
#include 
#include 

using namespace std;

volatile int counter = 0;
std::mutex mtx;

void ft1()
{
    for (int i = 0; i < 100000; ++i)
    {
        mtx.lock();
        ++counter;
        mtx.unlock();
    }
}

int main()
{
    std::vector ts;
    for(int i = 0; i < 5; ++i)
    {
        ts.emplace_back(std::thread(ft1));
    }

    for (auto& t : ts)
    {
        t.join();
    }

    cout << counter << endl;
    system("pause");
    return 0;
}

输出结果: counter 等于 5 * 100000

测试发现在加锁的情况下,输出结果会慢很多,网上查阅c++11的mutex性能损耗比较大。

2. std::promise

#include 
#include 
#include 

using namespace std;

volatile int counter = 0;

void ft1(std::future& fut)
{
    int x = fut.get();

    cout << "x = " << x << "\n";
}

int main()
{
    std::promise prom;
    std::future fut = prom.get_future();

    std::thread t(ft1, std::ref(fut));
    prom.set_value(10);  // 注释该句ft1线程阻塞,知道fut.get()获取到set_vaule()的值
    t.join();

    system("pause");
    return 0;
}

3. std::atomic

#include 
#include 
#include 
#include 
#include 

using namespace std;

std::atomic counter(0);

void ft1()
{
    for (int i = 0; i < 100000; ++i)
    {
        ++counter;
    }
}

int main()
{
    std::vector ts;
    for(int i = 0; i < 5; ++i)
    {
        ts.emplace_back(std::thread(ft1));
    }

    for (auto& t : ts)
    {
        t.join();
    }

    cout << counter << endl;
    system("pause");
    return 0;
}

测试性能由于std::mutex

你可能感兴趣的:(C++11多线程同步方法)