Making something happen when increasing a variable - if-statement

How do I make it so that every time a variable increases I can do something like play a particle system
I have the variables coins1 through coins7 and every time one of them updates I need a trigger to happen

Related

c++: can I give a new value to a thread, while it is still running or do I have to end it first?

I have just started using threads when coding, and I'm not sure whether I understood properly how they work.
If I got it right, with a thread you can make two functions run at the same time. Is it possible to change the value given to one of the functions while it is still running in parallel?
In my case I read instructions from a csv file such as:
colAction=VELOCITY; colTime=0; colParam1=-30; colParam2=2;
colAction=VELOCITY; colTime=10; colParam1=-15; colParam2=0.4;
colAction=VELOCITY; colTime=0; colParam1=-10; colParam2=1;
colAction=VELOCITY; colTime=45; colParam1=-60; colParam2=11;
colAction=TEMPERATURE; colTime=120; colParam1=95;
colAction=TEMPERATURE; colTime=20; colParam1=57;
colAction=TEMPERATURE; colTime=25; colParam1=95;
colAction=LOOP; colParam1=22; colParam2=7; colParam3=23;
colAction=TEMPERATURE; colTime=20; colParam1=95;
colAction=VELOCITY; colTime=0; colParam1=-10; colParam2=11;
colAction=VELOCITY; colTime=1; colParam1=-1; colParam2=5;
colAction=VELOCITY; colTime=5; colParam1=-20; colParam2=11;
I have a function that sets a temperature and a function that sets a velocity. the parameter colTime tells me how long I have to hold the velocity or the temperature, without following the next instruction. when the colTime has expired, I need to follow the next instruction: if a temperature is followed by another temperatur I just give the function the next value, but if temperature is followed by velocity, I need to keep the temperature function running, while starting the velocity function.
The problem arises, when after setting temperature then velocity follows another temperature. Now I need to keep the velocity running and setting another temperature. And I don't know how to do this.
I hope I could make my problem clear somehow and it is not too confused.
Typically a process can be seen a stack of function/procedure/method calls. At any point in time your program will be in a single point of your code.
When we add multiple threads into the program, instead of a single stack, we now will have multiple stacks of function/procedure/method calls. Each of them will be at any point in time in a different points of your code.
In C/C++, your main thread (the one that started it all) will have at the bottom of the stack the int main(int argc,char**argv) function. That applies to both single threaded and the main thread of a multithreaded program.
How about the rest of the threads. Well, for each of them you will specify a starting function. Threads (and main threads) will start execution at the beginning of the start function and run til the end. The thread will be alive while its starting function is being executed.
Now thinking of your code. One of many possibilities is spawn a thread to execute your temperature or velocity functions. That would be your starting function for newly spawned thread. You can join() from the spawning thread to wait for it to complete.
The thing about threads vs. other multiprocessing ways of organizing code (e.g. heavy processes) is that although we've seen that each of the threads have its own call stack, they all share the same memory.
So, while is not possible to modify the arguments of the thread starting function (that train has already passed)... However, other parts of the code could simply change some value in the memory (which is shared) and the starting function of the thread could be periodically checking that memory to detect the change and modify its behaviour.
But that brings a different problem: accessing/reading/writing shared memory potentially from multiple threads can lead to unpredictable results. So (any kind of) access must be protected with some sort of synchronization (mutexes, atomics...)

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

How change the life time of existing particles in CCParticleSystemQuad?

I have a CCParticleSystemQuad and it generated many particles with setLifeVaule(40).
Now, in the runtime, I want to change the life value of the existing particles in fewer value such as 0.1.
But setLife() function does not affect existing particles.how can i change the life Time of them?

create object based on time in 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.

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.