Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/144.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ c+中的微螺纹+;_C++_Multithreading_C++11 - Fatal编程技术网

C++ c+中的微螺纹+;

C++ c+中的微螺纹+;,c++,multithreading,c++11,C++,Multithreading,C++11,是否可以使用std库为应用程序中的每个线程保留内存?我想创建一些微线程,我想知道如何为每个线程保留内存,如果可能,为线程分配内存的最佳做法是什么。如果每个线程需要不同的静态内存,但指针相同,则可以使用线程本地存储: #include <thread> #include <iostream> static thread_local char thread_name[40]; // on older compilers use __thread void thread1(

是否可以使用std库为应用程序中的每个线程保留内存?我想创建一些微线程,我想知道如何为每个线程保留内存,如果可能,为线程分配内存的最佳做法是什么。

如果每个线程需要不同的静态内存,但指针相同,则可以使用线程本地存储:

#include <thread>
#include <iostream>

static thread_local char thread_name[40]; // on older compilers use __thread

void thread1() {
    strcpy(thread_name, "T1");

    for (int i = 0; i < 10; ++i)
       std::cerr << thread_name << ": I'm thread1!\n";
}

void thread2() {
    strcpy(thread_name, "T2");

    for (int i = 0; i < 10; ++i)
       std::cerr << thread_name << ": I'm thread2!\n";
}

int main() {
  std::thread t1(thread1), t2(thread2);
  t1.join(); t2.join();
}
#包括
#包括
静态线程\本地字符线程\名称[40];//在较旧的编译器上使用_线程
void thread1(){
strcpy(螺纹名称,“T1”);
对于(int i=0;i<10;++i)

标准支持线程本地内存。任何线程分配的内存都可以被任何其他线程访问,这是对的。但是如果只有一个线程有指向该内存的指针,那么他将是唯一访问该内存的线程。只有当同一个函数/对象被多个线程访问时,才需要线程本地内存,并且您可以为什么是编译器扩展而不是
thread\u local
变量?没错,我是从GCC4.4兼容代码粘贴的,我编辑了我的答案。