c++复习-基础-从c到c++-类型限定符+存储类限定符+引用

时间:2024-01-26 16:42:07

thread_local

  • c++11
  • 用于声明线程局部存储的变量。线程局部存储意味着每个线程都有其自己独立的变量实例,不同线程之间的变量互不影响
  • thread_local 说明符可以与 static 或 extern 合并。
  • 可以将 thread_local 仅应用于数据声明和定义,thread_local 不能用于函数声明或定义

编译命令是:g++ -std=c++11 hello.cpp -o hello -pthread

(base) [p@localhost ~]$ g++ -std=c++11  hello.cpp -o hello 
(base) [p@localhost ~]$ ./hello
terminate called after throwing an instance of 'std::system_error'
  what():  Enable multithreading to use std::thread: Operation not permitted
已放弃(吐核)
(base) [p@localhost ~]$ g++ -std=c++11  hello.cpp -o hello -pthread
#include <iostream>
#include <thread>

thread_local int threadLocalVariable = 0;

void exampleFunction() {
    // 修改线程局部变量
    threadLocalVariable++;
    // 输出结果
    std::cout << "Thread ID: " << std::this_thread::get_id() << ", Thread Local Variable: " << threadLocalVariable << std::endl;
}

int main() {
    // 创建两个线程并调用函数
    std::thread thread1(exampleFunction);
    std::thread thread2(exampleFunction);

    // 等待线程执行完毕
    thread1.join();
    thread2.join();

    return 0;
}