16
edits
Changes
→C++11 Threading - adding example
The code above gives a simple example on how threads are created and joined back to the parent thread in the end.
=== Usage of C++11 Threading ===
<syntaxhighlight lang="cpp">
#include <thread>
#include <iostream>
#include <chrono>
#include <vector>
#include <mutex>
#define MAX_THREAD 16
std::mutex mtx; //creates critical section
int main() {
const int iteration = 100000000;
const int runs = 5;
for (int x = 0; x < MAX_THREAD; x++) { //iteration over the max amount of cores.
auto t = 0;
int count = 0;
for (int y = 0; y < runs; y++) {
count = 0;
std::vector<std::thread> threads;
//setting the remainder count outside of count, neglectible at larger iteration, max value of number of thread - 1
for (int i = 0; i < iteration % (x + 1); i++) {
count++;
}
std::chrono::steady_clock::time_point ts = std::chrono::steady_clock::now();
for (int j = 0; j < x + 1; j++) {
threads.push_back(
std::thread([x, iteration, &count]() {
mtx.lock();
for (int k = 0; k < iteration / (x + 1); k++) {
count++;
}
mtx.unlock();
}));
}
for (auto& thrd : threads) {
thrd.join();
}
std::chrono::steady_clock::time_point te = std::chrono::steady_clock::now();
auto temp = std::chrono::duration_cast<std::chrono::milliseconds>(te - ts);
t += temp.count();
}
std::cout <<"C11 Thread - Counting to: " << count << " - Number of threads created: " << x+1 << " | elapsed time: " << t/runs << " ms" << std::endl;
}
}
</syntaxhighlight>
<syntaxhighlight lang="cpp">
C11 Thread - Counting to: 100000000 - Number of threads created: 1 | elapsed time: 243 ms
C11 Thread - Counting to: 100000000 - Number of threads created: 2 | elapsed time: 238 ms
C11 Thread - Counting to: 100000000 - Number of threads created: 3 | elapsed time: 241 ms
C11 Thread - Counting to: 100000000 - Number of threads created: 4 | elapsed time: 224 ms
C11 Thread - Counting to: 100000000 - Number of threads created: 5 | elapsed time: 225 ms
C11 Thread - Counting to: 100000000 - Number of threads created: 6 | elapsed time: 224 ms
C11 Thread - Counting to: 100000000 - Number of threads created: 7 | elapsed time: 228 ms
C11 Thread - Counting to: 100000000 - Number of threads created: 8 | elapsed time: 225 ms
C11 Thread - Counting to: 100000000 - Number of threads created: 9 | elapsed time: 223 ms
C11 Thread - Counting to: 100000000 - Number of threads created: 10 | elapsed time: 231 ms
C11 Thread - Counting to: 100000000 - Number of threads created: 11 | elapsed time: 226 ms
C11 Thread - Counting to: 100000000 - Number of threads created: 12 | elapsed time: 225 ms
C11 Thread - Counting to: 100000000 - Number of threads created: 13 | elapsed time: 222 ms
C11 Thread - Counting to: 100000000 - Number of threads created: 14 | elapsed time: 225 ms
C11 Thread - Counting to: 100000000 - Number of threads created: 15 | elapsed time: 226 ms
C11 Thread - Counting to: 100000000 - Number of threads created: 16 | elapsed time: 223 ms
</syntaxhighlight>
== OpenMP Threading ==