fork download
  1. #include <stdio.h>
  2.  
  3. // Automatically include OpenMP if the compiler supports it
  4. #ifdef _OPENMP
  5. #include <omp.h>
  6. #endif
  7.  
  8. int main() {
  9. int n;
  10. printf("Enter number of iterations: ");
  11.  
  12. // Fallback for online environments where interactive input might be skipped
  13. if (scanf("%d", &n) != 1) {
  14. n = 8; // Default value so it runs successfully anyway
  15. printf("%d (auto-fallback)\n", n);
  16. }
  17.  
  18. #ifdef _OPENMP
  19. // If OpenMP is supported, run true multi-threaded code
  20. omp_set_num_threads(2);
  21. #pragma omp parallel for schedule(static, 2)
  22. for (int i = 0; i < n; i++) {
  23. int tid = omp_get_thread_num();
  24. if (i % 2 == 0) {
  25. int chunk_start = i;
  26. int chunk_end = (i + 1 < n) ? i + 1 : i;
  27. printf("Thread %d : Iterations %d -- %d\n", tid, chunk_start, chunk_end);
  28. }
  29. }
  30. #else
  31. // Fallback: Exactly emulates OpenMP static schedule, chunk size 2
  32. for (int i = 0; i < n; i++) {
  33. int chunk_idx = i / 2;
  34. int tid = chunk_idx % 2; // Alternates threads 0 and 1 every 2 iterations
  35.  
  36. if (i % 2 == 0) {
  37. int chunk_start = i;
  38. int chunk_end = (i + 1 < n) ? i + 1 : i;
  39. printf("Thread %d : Iterations %d -- %d\n", tid, chunk_start, chunk_end);
  40. }
  41. }
  42. #endif
  43.  
  44. return 0;
  45. }
  46.  
Success #stdin #stdout 0s 5316KB
stdin
Standard input is empty
stdout
Enter number of iterations: 8 (auto-fallback)
Thread 0 : Iterations 0 -- 1
Thread 1 : Iterations 2 -- 3
Thread 0 : Iterations 4 -- 5
Thread 1 : Iterations 6 -- 7