#include <iostream>
#include <vector>
#include <queue>
#include <thread>
#include <atomic>
#include <chrono>
#include <mutex>
class MyClass {
public:
MyClass() {
message = new char[2048];
}
~MyClass() { delete message; }
private:
char* message;
};
// Function to create objects
std::vector<MyClass*> createObjects(size_t numObjects) {
std::vector<MyClass*> objects;
objects.reserve(numObjects);
for (size_t i = 0; i < numObjects; ++i) {
objects.push_back(new MyClass());
}
return objects;
}
// Function to delete objects in a thread
void deleteObjects(std::queue<MyClass*>& objectsQueue) {
auto start = std::chrono::high_resolution_clock::now();
size_t deletetime = 0;
while (!objectsQueue.empty()) {
delete objectsQueue.front();
objectsQueue.pop();
}
auto end = std::chrono::high_resolution_clock::now();
deletetime += std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
std::cout << "thread deletion time: " << deletetime << " ms" << std::endl;}
int main() {
const size_t numObjects = 20000000;
const size_t numThreads = 4;
// Step 1: Create all objects
std::vector<MyClass*> objects = createObjects(numObjects);
// Step 2: Divide objects among threads
std::vector<std::queue<MyClass*>> threadQueues(numThreads);
for (size_t i = 0; i < numObjects; ++i) {
threadQueues[i % numThreads].push(objects[i]);
}
// Step 3: Delete objects in threads
std::vector<std::thread> threads;
for (size_t i = 0; i < numThreads; ++i) {
threads.emplace_back(deleteObjects, std::ref(threadQueues[i]));
}
// Join all threads
for (auto& thread : threads) {
thread.join();
}
return 0;
}
I run above code on visual studio 2017 on windows 10
result is
thread deletion time: 1086 ms
thread deletion time: 1252 ms
thread deletion time: 1259 ms
thread deletion time: 62670 ms
3 threads are fast, but last one takes too long.
Does any one know why this is happened?
I expect all thread done that tasks almost same time.
New contributor
user25518974 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.