Use of #pragma in C

前端 未结 10 1761
囚心锁ツ
囚心锁ツ 2020-11-27 09:32

What are some uses of #pragma in C, with examples?

10条回答
  •  北海茫月
    2020-11-27 10:22

    All answers above make nice explanations for #pragma but I wanted to a add small example

    I just want to explain a simple OpenMP example that demonstrate some uses of #pragma to doing its work

    OpenMp briefly is an implementation for multi-platform shared-memory parallel programming (then we can say it's machine-specific or operating-system-specific)

    let's go to the example

    #include 
    #include // compile with: /openmp
    
    int main() {
       #pragma omp parallel num_threads(4)
       {
          int i = omp_get_thread_num();
          printf_s("Hello from thread %d\n", i);
       }
    }
    

    the output is

    Hello from thread 0
    Hello from thread 1
    Hello from thread 2
    Hello from thread 3
    
    Note that the order of output can vary on different machines.
    

    now let me tell you what #pragma did...

    it tells the OS to run the some block of code on 4 threads

    this is just one of many many applications you can do with the little #pragma

    sorry for the outside sample OpenMP

提交回复
热议问题