-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmultithread.h
More file actions
42 lines (32 loc) · 1.28 KB
/
Copy pathmultithread.h
File metadata and controls
42 lines (32 loc) · 1.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#ifndef MULTITHREAD_H
#define MULTITHREAD_H
#include "video.h"
template <typename Func>
void multiThread(Video &video, Func function) {
std::vector<std::thread> threads;
size_t numFrames = video.numFrames;
// Get number of available threads for this specific device
size_t hardwareThreads = std::thread::hardware_concurrency();
// Error condition if return 0, then only try 2 threads
if (hardwareThreads == 0) {
hardwareThreads = 2;
}
size_t numThreads = std::min(hardwareThreads, numFrames);
size_t framesPerThread = numFrames / numThreads;
size_t remainingFrames = numFrames % numThreads;
int64_t startFrame, endFrame;
// Calculate the range of frames for the threads and start them
for (size_t threadIndex = 0; threadIndex < numThreads; threadIndex++) {
startFrame = threadIndex * framesPerThread;
endFrame = startFrame + framesPerThread;
if (threadIndex == numThreads - 1) {
endFrame += remainingFrames;
}
threads.emplace_back(function, startFrame, endFrame);
}
// Join all threads when finished so that there are no loose threads
for (size_t threadIndex = 0; threadIndex < numThreads; threadIndex++) {
threads[threadIndex].join();
}
}
#endif // MULTITHREAD_H