void queue_test() { std::cout << "starting queue test" << std::endl; PriorityQueue<int> queue; const int OPERATIONS_PER_THREAD = 500; const int THREADS_COUNT = 20; auto filler = [&]() { for (size_t index = 0; index < OPERATIONS_PER_THREAD; ++index) { queue.add(index, index); } }; auto getter = [&]() { for (size_t index = 0; index < OPERATIONS_PER_THREAD; ++index) { queue.getMin(); } }; auto worker = [=](std::function<void()> func) { std::vector<boost::thread> threads; for (size_t index = 0; index < THREADS_COUNT; ++index) { threads.emplace_back(func); } for (auto & it : threads) { it.join(); } }; std::cout << "start filling" << std::endl; worker(filler); std::cout << "size after filling: " << queue.size() << std::endl; std::cout << "start getting" << std::endl; worker(getter); std::cout << "size after getting: " << queue.size() << std::endl; std::cout << "done" << std::endl; assert(queue.empty()); }
void addTask(const T & task, int priority) { std::unique_lock<std::mutex> lock(mutex); queue.add(task, priority); condition.notify_one(); }
/* * Function: kruskal * -------------------- * This function implements kruskal algorithm to create a minimum graph with all * vertexes connected with least cost or number of edges * * Preconditions: * * @param: graph: The graph to be minimized * * @return: returns a set of edges in the MST */ Set<Edge*> kruskal(BasicGraph& graph) { graph.resetData(); // Reset data jic PriorityQueue<Edge*> pq; // pq to hold the edges with least cost first Map<Vertex*, Set<Vertex*>*> mp; // Our cluster storing structure Set<Edge*> mst; // Our edge return set // PLace all edges into a pq with cost=priority for(Edge* e:graph.getEdgeSet()){ pq.add(e,e->cost); } // Make clusters through map structure for(Vertex* v:graph.getVertexSet()){ Set<Vertex*>* clusterSet = new Set<Vertex*>; clusterSet->add(v); mp.add(v,clusterSet); } // While the priority queue is not empty while(!pq.isEmpty()){ Edge* e = pq.dequeue(); Vertex* v1 = e->start; Vertex* v2 = e->end; // If the pointers point to the same Set, they must // be connected if(mp[v1]!=mp[v2]){ // Make a temporary pointer to v2's Set Set<Vertex*>* tempPointer = mp[v2]; // Set all clusters in v2's set to point to v1's set for(Vertex* v:*tempPointer){ mp[v1]->add(v); Set<Vertex*>* tempPointer2 = mp[v]; mp[v] = mp[v1]; // Dont delete same pointer twice if(tempPointer2!=tempPointer) delete tempPointer2; } // Delete abandoned memory delete tempPointer; // Add edge e to MST mst.add(e); } } // Free large cluster of memory for(Vertex* v:mp){ Set<Vertex*>* toDelete = mp[v]; delete toDelete; break; } return mst; }