C++ thread_local - 线程存储期

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/flyfish1986/article/details/80700295

C++ thread_local - 线程存储期

flyfish

环境:vs2017

content相当于各个线程都有一份拷贝
第一个例子

#include "stdafx.h"
#include <iostream>
#include <string>
#include <thread>
#include <mutex>
#include <atomic>
#include <vector>
#include <numeric>


thread_local std::vector<int> content;
std::mutex cout_mutex;

std::atomic<int> sum=0;

void insert_data(const std::string& thread_name)
{
    for (int i = 1; i < 3; i++)
        content.push_back(i);

     sum = std::accumulate(content.begin(), content.end(), 0);
    std::lock_guard<std::mutex> lock(cout_mutex);
    std::cout << "sum " << thread_name << ": " << sum << '\n';
}

int main()
{

    std::thread a(insert_data, "a"), b(insert_data, "b");

    a.join();
    b.join();
    system("pause");
}

sum a: 3
sum b: 3

第二个例子

#include "stdafx.h"
#include <iostream>
#include <string>
#include <thread>
#include <mutex>
#include <atomic>

thread_local unsigned int rage = 1;
std::mutex cout_mutex;

void increase_rage(const std::string& thread_name)
{
    ++rage; // 在锁外修改 OK ;这是线程局域变量
    std::lock_guard<std::mutex> lock(cout_mutex);
    std::cout << "Rage counter for " << thread_name << ": " << rage << '\n';
}

int main()
{
    std::thread a(increase_rage, "a"), b(increase_rage, "b");

    {
        std::lock_guard<std::mutex> lock(cout_mutex);
        std::cout << "Rage counter for main: " << rage << '\n';
    }

    a.join();
    b.join();
    system("pause");
}

运行结果
std::atomic rage = 1;

Rage counter for a: 2
Rage counter for main: 3
Rage counter for b: 3

thread_local unsigned int rage = 1;

Rage counter for a: 2
Rage counter for b: 2
Rage counter for main: 1

展开阅读全文

没有更多推荐了,返回首页