3

Is the following code is compile time recursive? I would like to know how to confirm this i.e any debugger,profiler etc to understand template programs.

#include <iostream>
#include <vector>
#include <thread>
std::vector<std::thread> vecc;

void thread_fn(){
    std::cout<<"Thread function"<<"\n"; 
}

template <int n>
void create_thread(){
    create_thread<n-1>();
    vecc.push_back(std::thread(thread_fn));
}
template<>
void create_thread<0>(){
    vecc.push_back(std::thread(thread_fn));
}

int main()
{
    create_thread<10>();
    for(auto &a: vecc){
        a.join();
    }
}
9
  • What is your question? Commented Nov 29, 2017 at 11:01
  • Despite what you're asking, I don't think threads can be spawned at compile time. Commented Nov 29, 2017 at 11:03
  • 1
    The generated code for create_thread<10>() has the same meaning as 10 lines of vecc.push_back(std::thread(thread_fn)), if that's what you are asking Commented Nov 29, 2017 at 11:09
  • Related (but more broad) stackoverflow.com/questions/7325910/… Commented Nov 29, 2017 at 11:18
  • The templates are recursive and templates are instantiated at compile-time, so... Commented Nov 29, 2017 at 11:51

1 Answer 1

3

For gcc you can use -fdump-tree-original option:

g++ -fdump-tree-original -Wall -pthread 111.cpp

Now you can see how create_thread template is getting instantiated in generated dump:

$ grep create_thread 111.cpp.003t.original
;; Function void create_thread() [with int n = 0] (null)
  create_thread<10> () >>>>>;
;; Function void create_thread() [with int n = 10] (null)
  create_thread<9> () >>>>>;
;; Function void create_thread() [with int n = 9] (null)
  create_thread<8> () >>>>>;
;; Function void create_thread() [with int n = 8] (null)
  create_thread<7> () >>>>>;
;; Function void create_thread() [with int n = 7] (null)
  create_thread<6> () >>>>>;
;; Function void create_thread() [with int n = 6] (null)
  create_thread<5> () >>>>>;
;; Function void create_thread() [with int n = 5] (null)
  create_thread<4> () >>>>>;
;; Function void create_thread() [with int n = 4] (null)
  create_thread<3> () >>>>>;
;; Function void create_thread() [with int n = 3] (null)
  create_thread<2> () >>>>>;
;; Function void create_thread() [with int n = 2] (null)
  create_thread<1> () >>>>>;
;; Function void create_thread() [with int n = 1] (null)
  create_thread<0> () >>>>>;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.