create object based on time in c++ - c++

i am writing a simulation about vehicle manufacturing, i am wondering how i can create objects based on time..
i have a base class Vehicle, and children Motorbike, Car, and Truck.
1 Motorbike will be manufactured every 1 hour,
1 car will be manufactured every 3 hours,
and 1 truck will be manufactured every 8 hours.
how can i create those objects according to the time indicated?
thanks

One possibility is to have a thread dedicated to each task, that just sits in a loop of lather, rinse,create, sleep, repeat.

You can create timers and wait on those timer events.
When the timer expires you can create corresponding object.
You can monitor this in a thread.
When will you be destroying these objects?

If you want to have complete control over the timing (say, you can increment the time irrespective of the system timer), then you'll need to implement that as a class. Then provide a Singleton or static function to return the Current time. The time class should be copyable so that objects can remember the starting time. Also, provide a function for advancing time by a certain amount, and for doing time comparisons.
Inside each manufacturable object (or better, the factories that manufacture them), add two functions:
StartManufacture. This function should remember the starting time.
CheckManufactureComplete. This function fetches the current time, and checks if the required waiting time has elapsed since manufacturing started.

Related

Unable to fix score trap issue in Optaplanner for a variation of the Task Scheduling Problem

I am working on a variation of the Task scheduling problem. Here are the rules:
Each Task has a start time to be chosen by the optimizer
Each Task requires multiple types of resources (Crew Members) who work in parallel to complete the task. i.e the task can start only when all required types of crew members are available.
There are multiple crew members of a certain type and the optimizer has to choose the crew member of each type for a task. Eg Task A requires an Electrician and a Plumber. There are many electricians and plumbers to choose from.
Here is my domain.
I have created a planning entity called TaskAssignment with 2 planning variables CrewMember and Starttime.
So, if a Task requires 3 types of crew members, then 3 TaskAssignment entities would be associated with it.
I placed a hard constraint to force the Starttime planning variable to be same for all the TaskAssignments corresponding to a particular task.
This works perfectly when I do not add any soft constraints (For example to reduce the total cost of using the resources). But when I add the soft constraint, there seems to be a violation of 1 hard constraint.
My guess if that this is due to a score trap because the starttimes are not changing as a set.
Note: I have tried to avoid using the PlanningList variable. Can anyone suggest a way to solve this issue ?
Your issue appears to be that your scoring function expects all employees on a given task to move simultaneously, but the solver actually moves them one by one. This is a problem in your domain model - it allows this situation to happen, because you only ever assign one employee at a time.
There are two ways of fixing this problem:
Fix your model, so that this is not allowed. For example, if you know that each task requires two people, let there be two variables on the entity, one for each employee. If there is a certain maximum of people per task, have a variable for each, and make them nullable, so that unassigned slots are not an issue. If you don't have a fixed amount of employees per task and you can not get to a reasonable maximum, then this approach will likely not work for you. In that case...
Write coarse-grained custom moves which always move all the employees together.

Run two function simultaniously (at the same time) in C++

I am programming a robot with QT (C++).
I have a function move_gripper() which closes or opens the gripper (it depends on the parameter) and a function relative_motion() which lets the end effector move downwards. What I want to do is to close the gripper ( calling the move_gripper() function ) while moving the robot downwards ( calling the relative_motion() function )
The execution time of the functions are not the same ( let's say move_gripper() lasts 2 seconds while relative_motions() lasts 3 seconds ). I want the two functions to start the execution at the same time.
In computer theory there is no real "simultaneously".
The common approach is to use threads. Those threads are executed, halted, switched just so fast it looks like they are executed simultaneously.
But still there are some things which can be done wrong which make the usage of threads even worse than not to use them.
So I would say first get some knowledge about threads (see the link: https://doc.qt.io/qt-5/qthread.html) and create 2 threads, one for each channel and do your work in there.

Cleaning object pool based on execution time

Problem
My current project implements a pool of objects to avoid constant memory allocation and de-allocation for speed purposes, the object pool is a std::vector<object> and I would like to implement a form of garbage collection to reduce memory usage and increase performance. Every loop the program iterates over the entire vector and if the object is active, executes the update function, this means that if my vector is full of inactive objects, I will be wasting a lot of time iterating over them and also memory storing them. I cannot clean the vector every frame as this would crush performance.
Current attempt
My current attempt at implementing this has been to measure the update time, and use a pre-defined function to determine whether or not we are spending too much time on the update, for the amount of objects currently active, if we are, I clean the vector once to allow the speed to return to normal.
#include <chrono>
void updateObjects()
{
auto begin = std::chrono::high_resolution_clock::now();
//update all objects
for(auto o : objectVec)
{
//only update active objects
if(o.m_alive)
{
o.update();
}
}
//end time of update
auto end = std::chrono::high_resolution_clock::now();
//calculate time taken vs estimated time
auto elapsed = (end-begin).count();
//Estimate is based on performance testing
long estimate = 25*m_particleCount+650000;
//If we have no active objects,
//but are wasting memory on storing them, we clean up
//If the update takes longer than it should, we clean up
if(((objectCount <= 0) && (objectVec.size() > 0)) || (elapsed > estimate))
{
cleanVec(); //remove inactive objects
}
}
This solution works well on my pc, however I am having issues with it on other computers as the time taken for the update to complete varies due to different CPU speeds, and my pre-defined function then doesn't work as it is based off of incorrect data. I am wondering if there is another measurement I can use for this calculation? Is there a way I can measure the pure amount of instructions executed, as this would be the same across computers, some would simply execute them faster? Any other suggestions are welcome, thank you!
Edit
The object pool can be as large as 100,000 objects, typical usage will range from 3000 to the maximum.
My function for cleaning is:
objectVec.erase(std::remove_if(objectVec.begin(),
objectVec.end(),
[](const object& o) {return !(o->m_alive);}),
objectVec.end());
Typically, an object pool uses aging to determine when to expel an individual pool object.
One way to do that is to keep an iteration counter within your update loop. This counter would be incremented every loop. Each object could keep a "last active" time (the loop count the last time the object was active). Inactive objects would be moved to the end of the array, and when old enough would be expelled (destroyed). A separate index of the last active object would be kept, so looping for updates could stop when this was encountered.
If it isn't possible to store an active time in an object, you can still move the inactive objects to the end of the active list, and if there are too many inactive objects pare the list down some.
You should specify how expensive your cleanup is, and how large your pool is, they affect how cleaning up should be implemented.
To make it clear, the pool is effectively an allocator of one type of object and performance gains are completely independent of how individual objects are cleaned up.
I cannot clean the vector every frame as this would crush performance.
If the performance of inactive objects' cleanup dominates, there is nothing you can do in your pool algorithm.
Therefore I assume this is due to std::vector semantics where removing inactive objects involves relocation of other objects. It is then logical to ask do you really need std::vector's properties?
Do you need your objects to be contiguous in memory?
Do you need O(1) random access?
Do you loop over the pool constantly?
Otherwise, is the pool small? As long as it is small std::vector is fine.
If the answer is no, then just use stuff like std::deque and std::list, where removal is O(1) and you can cleanup on every frame.
Otherwise garbage collection of your pool can be done as
keeping a counter of frames since last updated for each object, remove if counter is over a threshold
keeping a counter of total inactive objects, clean pool if percentage of active objects is over a threshold

C++/QT/OpenMP : Threads seems to wait when access to the same instance

I use C++, Qt and OpenMP on a algorithm which make some process on a graph (arcs and nodes). The class Node use a static class which manage the graph (class Graph) with adjacency list of pointers on nodes. I can ask the successors or predecessors of a node and I receive a QList of pointer on nodes.
The goal is to find some constrained paths in the graph.
I use OpenMP to parallelize the algorithm. A good point is each thread has his own list of tasks and no resources need to be shared or protected by mutual exclusion. But each thread reads the same instance of the graph or read some information on the nodes. Graph and nodes are shared, but only for reading.
When I use n threads, the computation time is n times the sequential time. Why? Are the threads waiting if they use the same method on a same instance? All the Qt structures I use are reentrant. Mine should be too, except for the fact that I use static members. But nothing is modifying.
Any ideas ?
Ok, I found the problem. I use QDateTime and I often use toTime_t() to convert the date into integer. It's time consuming. I thought the integer was a member. I think it computes each time the date.
But I don't understand the difference of time I had. If I use 1 thread, the parallel part takes 400ms. If I divide the problem into 4 threads it takes 1600ms in parallel !! But if I execute the 4 threads one by one, each takes 100ms with a total of 400ms. Does the function use system call or use a thread-safe static conversion ?
Anyway, now it works fine ! I store one time the result of toTime_t() inside my class.

C++ class - Increment and decrement attribute every N milliseconds

This must be an easy question but I can't find a properly answer to it.
I'm coding on VS-C++. I've a custom class 'Person' with attribute 'height'. I want to call class method Grow() that starts a timer that will increment 'height' attribute every 0.5 seconds.
I'll have a StopGrow() that stops the timer and Shrink() that decrements instead of increment.
I really need a little push on which timer to use and how to use it within Grow() method. Other methods must be straight forward after knowing that.
That's my first question here so please be kind (and warn me if I'm doing it wrong :) Forgive my English, not my first language.
Do you really need to call the code every half second to recalculate a value? For most scenarios, there is another much simpler, faster, effective way.
Don't expose a height member, but use a method such as GetHeight(), which will calculate the height at the exact moment you need it.
Your Grow() method would set a base height value and start time and nothing else. Then, your GetHeight() method would subtract the starting time from the current time to calculate the height "right now", when you need it.
No timers needed!
Since you're on Windows, the simplest solution is probably to use the GetTickCount() function supplied by Windows.
There isn't a good timer function in the C++ language with a precision guaranteed to be less than a second.
So instead, include the windows.h header, and then call GetTickCount() to get a number of milliseconds. The next time you call it, you simlpy subtract the two values, and if the result is over 500, half a second has elapsed.
Alternatively, if you want to block the thread for half a second, use the Sleep(n) function, where n is the number of milliseconds you want the thread to sleep. (500 in your case)
You might want to take a look at CreateTimerQueue() and CreateTimerQueueTimer(). I've never personally used them, but they would probably fit the bill.
I currently spawn a thread that is responsible for doing timer based operations. It calls WaitForSingleObject() on a manual-reset event with a 10ms timeout. It keeps an internal collection of callbacks in the form of pointer-to-method and objects that the callbacks are invoked for. This is all hidden behind a singleton that provides a scheduler interface that let's the caller schedule method calls on the objects either after a timer expiration or regularly on an interval. It looks like the two functions that I mentioned should give you pretty much the same functionality... hmmm... might be time to revisit that scheduler code... ;-)
Sleep() an the normal timer event run off a 10ms clock.
For high resolution timer events on windows use high resolution timers
Not an easy question at all! You have at least two possibilities:
create a thread that will execute a loop: sleep 0.5s, increase height, sleep 0.5s, increase height, etc.
invert flow of control and pass it to some framework like Boost::Asio that will call your timer handler in every 0.5s.
In order to make the right decision you have to think about your whole application. Does it compute something (then maybe threads)? Does it interact with the user (then maybe event driven)? Each approach has some gotchas:
When you use threads you have to deal with locking, which can be tricky.
When you do event-driven stuff, you have to write asynchronous handlers, which can be tricky.