美文网首页
C++11多线程同步方法

C++11多线程同步方法

作者: soul_5264 | 来源:发表于2017-05-23 21:15 被阅读0次

std::mutex

#include <iostream>
#include <vector>
#include <mutex>
#include <thread>

using namespace std;

volatile int counter = 0;

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

int main()
{
    std::vector<std::thread> 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 <iostream>
#include <vector>
#include <mutex>
#include <thread>

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<std::thread> 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 <iostream>
#include <thread>
#include <future>

using namespace std;

volatile int counter = 0;

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

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

int main()
{
    std::promise<int> prom;
    std::future<int> 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<T>

#include <iostream>
#include <vector>
#include <mutex>
#include <thread>
#include <atomic>

using namespace std;

std::atomic<int> counter(0);

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

int main()
{
    std::vector<std::thread> 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多线程同步方法

      本文链接:https://www.haomeiwen.com/subject/lamgxxtx.html