|
| 1 | +#include <iostream> |
| 2 | +#include <omp.h> |
| 3 | + |
| 4 | +int main() { |
| 5 | + std::cout << "Program starting..." << std::endl; |
| 6 | + |
| 7 | + // Optional: Set the number of threads programmatically |
| 8 | + // omp_set_num_threads(4); // Or use OMP_NUM_THREADS environment variable |
| 9 | + |
| 10 | + // This pragma marks the start of a parallel region. |
| 11 | + // The code inside the {} block will be executed by multiple threads. |
| 12 | + #pragma omp parallel |
| 13 | + { |
| 14 | + // Get the unique ID of the current thread |
| 15 | + int thread_id = omp_get_thread_num(); |
| 16 | + |
| 17 | + // Get the total number of threads executing in this parallel region |
| 18 | + int num_threads = omp_get_num_threads(); |
| 19 | + |
| 20 | + // Each thread will print its own message |
| 21 | + // Using std::cout requires careful synchronization in more complex scenarios, |
| 22 | + // but for simple prints like this, it's often okay, though output might interleave. |
| 23 | + // Using printf might be slightly safer for interleaved output in simple cases. |
| 24 | + #pragma omp critical // Ensures only one thread prints at a time to avoid garbled output |
| 25 | + { |
| 26 | + std::cout << "Hello from thread " << thread_id |
| 27 | + << " out of " << num_threads << " threads." << std::endl; |
| 28 | + } |
| 29 | + |
| 30 | + // Example of work done by each thread (optional) |
| 31 | + // #pragma omp for // Could add a parallel loop here if needed |
| 32 | + // for(int i=0; i < 5; ++i) { |
| 33 | + // printf("Thread %d processing item %d\n", thread_id, i); |
| 34 | + // } |
| 35 | + |
| 36 | + } // End of the parallel region |
| 37 | + |
| 38 | + std::cout << "Parallel region finished." << std::endl; |
| 39 | + std::cout << "Program finished." << std::endl; |
| 40 | + |
| 41 | + return 0; |
| 42 | +} |
0 commit comments