I have 4 nodes in my simulation, in the code i check on a flag.
If it is become true during the run of any node then >> i want to stop the execution for all the nodes and go to execute finish method for each node.
I try to do as following but it doesn't call finish method!
if(flag == true)
{ finish();
abort();
}
How i can do it?
Thanks,
Have you tried this command?
endSimulation();
It ends the simulation, however I am not sure if it runs finish method or not..
Related
I am currently writing a program where I need to run a loop that can be interrupted at any time. In this case, a series of tones are playing over and over again but should stop when one of the values from a sensor comes back as HIGH.
At the moment, I've got this:
void loop() {
while(digitalRead(ctsPin) == LOW) {
// Some code here
}
}
However, the while loop will only break when the instructions inside it have finished running. Is there a way that I can run these over and over again but stop them at any time, even if it is part-way through?
Thanks in advance.
I take it that you are actually asking how to immediately break a loop which has many hard-coded delays (tones) in it, no matter what code inside that loop that is currently executing. That isn't possible.
Adding a lot of if statments all over the loop won't help, because that won't prevent delay-based code from playing out the current tone until it is done.
The alternative would be to create some sort of queue/ring buffer containing the items to be played. The PWM interrupt that plays the tones will go through this queue and play them one at a time.
When you wish to stop, you would then simply disable the interrupt and pull the port pin to a silent state. This will cause it to stop immediately, even if the program is playing the part between two edges of the tone signal.
The break statement will interrupt the current loop. So you should have a conditional statement for the condition you are monitoring, and if it evaluates to true, call break.
if (digitalRead(ctsPin) == HIGH){
break
}
Question is not clear. To stop running the loop you can use break as given below. Check if this is what you're looking for.
void loop() {
while(digitalRead(ctsPin) == LOW) {
// Some code here
if (digitalRead(ctsPin) == HIGH){
break;
}
// Some code here
}
}
There are two ways to break "instantly." One is to use an interrupt and the other is to check for the condition more often -- after each instruction if really necessary, and break out then:
void loop()
{
while(digitalRead(ctsPin) == LOW)
{
// code block (or even a single statement)...
if (digitalRead(ctsPin) == HIGH) break;
// code block (or even a single statement)...
if (digitalRead(ctsPin) == HIGH) break;
// code block (or even a single statement)...
if (digitalRead(ctsPin) == HIGH) break;
// etc.
}
}
If you get too many of these, it may be advisable then to look into an interrupt instead. For an example of how to do that, and the various interrupts available for your target board, I suggest taking a look at Arduino Interrupt Documentation.
If you decide to go that way, give it a try and then if you run into issues, ask a different question and we'll help you out.
I have a somewhat simple multithreaded application written using the C++ std::thread library for both Ubuntu 14.04 and Windows 8.1. The code is nearly completely identical except that I'm using the operating system respective libraries windows.h and unistd.h to use Sleep/sleep to pause execution for a time. They both actually begin to run and the Ubuntu version does keep running for a short time but then hangs. I am using the proper arguments to the sleep/Sleep functions since I know Windows Sleep takes milliseconds, while Unix sleep takes seconds.
I've run the code multiple times and on Ubuntu it never makes it past two minutes whereas I've run it on windows twice for 20 minutes and then multiple times for roughly five minutes each to see if I was just lucky. Is this just an incompatibility with the thread library or does sleep not do what I think it does, or something else? The infinite loops are there because this is a school project and is expected to run without deadlocks or crashing.
The gist is that this is a modified 4-way stop where cars who arrive first don't have to slow down and stop. We only had to let one car through the intersection at a time which takes 3 seconds to cross, hence Sleep(3000), and don't have to worry about turns. Three threads run the spawnCars function and there are four other threads that each monitor one of the four directions N, E, S, and W. I hope that it's understandable why I can't post the entire code in the chance some other student stumbles upon this. These two functions are the only place where code is different aside from the operating system dependent library inclusion at the top. Thanks.
edit: Since I've just gone and posted all the code for the project, if the problem does end up being a deadlock, may I request that you only say so, and not post an in depth solution? I'm new here so if that's against the spirit of SO then fire away and I'll try to figure it out without reading the details.
/* function clearIntersection
Makes a car go through the intersection. The sleep comes before the removal from the queue
because my understanding is that the wait condition simulates the go signal for drivers.
It wouldn't make sense for the sensors to tell a car to go if the intersection isn't yet
clear even if the lock here would prevent that.
*/
void clearIntersection(int direction)
{
lock->lock();
Sleep(3000);
dequeue(direction);
lock->unlock();
}
/* function atFront(int direction)
Checks whether the car waiting at the intersection from a particular direction
has permission to pass, meaning it is at the front of the list of ALL waiting cars.
This is the waiting condition.
*/
bool isAtFront(int direction)
{
lock->lock();
bool isAtFront = cardinalDirections[direction].front() == list->front();
lock->unlock();
return isAtFront;
}
void waitInLine()
{
unique_lock<mutex> conditionLock(*lock);
waitForTurn->wait(conditionLock);
conditionLock.unlock();
}
//function broadcast(): Let all waiting threads know they can check whether or not their car can go.
void broadcast()
{
waitForTurn->notify_all();
}
};
/* function monitorDirection(intersectionQueue,int,int)
Threads will run this function. There are four threads that run this function
in total, one for each of the cardinal directions. The threads check to see
if the car at the front of the intersectionQueue, which contains the arrival order
of cars regardless of direction, is the car at the front of the queue for the
direction the thread is assigned to monitor. If not, it waits on a condition
variable until it is the case. It then calls the function to clear the intersection.
Broadcast is then used on the condition variable so all drivers will check if they
are allowed to pass, which one will unless there are 0 waiting cars, waiting again if not the case.
*/
void monitorDirection(intersectionQueue *intersection, int direction, int id)
{
while (true) //Do forever to see if crashes can occur.
{
//Do nothing if there are no cars coming from this direction.
//Possibly add more condition_variables for each direction?
if (!intersection->empty(direction))
{
while (!intersection->isAtFront(direction))
intersection->waitInLine();
intersection->clearIntersection(direction);
cout << "A car has gone " << numberToDirection(direction) << endl;
//All cars at the intersection will check the signal to see if it's time to go so broadcast is used.
intersection->broadcast();
}
}
}
Your culprit is likely your while (!isAtFront(...)) loop. If another thread gets scheduled between the check and the subsequent call to waitInLine(), the state of your queues could change, causing all of your consumer threads to end up waiting. At that point there's no thread to signal your condition_variable, so they will wait forever.
Everything works great apart from the mutex. After I lock and unlock, it won't do anything. Is there something obvious I'm missing?
On top of this, after unlocking, I want to run a function inside this function. I've tried just calling it as a regular function (timer()) and even (go timer()).
func shield(state *State){
for s := range state.ToggleShield { //run if data on channel
if s == true { //if data on channel is true
fmt.Println("Opening the shields This is uninteruptable. Please wait...")
state.VariableMutex.Lock()
state.Finished = false //disable other commands
state.VariableMutex.Unlock()
fmt.Println("Move!!")
ticker := time.Tick(time.Second)
for i := 10; i >= 0; i-- {
<-ticker
fmt.Printf("\rOn 10/%d", i)
}
}
}
}
The Go Programming Language Specification
Go statements
A "go" statement starts the execution of a function call as an
independent concurrent thread of control, or goroutine, within the
same address space.
The function value and parameters are evaluated as usual in the
calling goroutine, but unlike with a regular call, program execution
does not wait for the invoked function to complete. Instead, the
function begins executing independently in a new goroutine. When the
function terminates, its goroutine also terminates.
Your program does not appear to have proper mechanisms to wait until your goroutines complete: "program execution does not wait for the invoked function to complete." To demonstrate this, I inserted a crude wait mechanism at the end of your program main function:
// wait for a while to give goroutines a chance to complete
time.Sleep(5 * time.Second)
Program: https://play.golang.org/p/ODdEihip4m
Output:
Toggling Shield
Opening the shields This is uninteruptable. Please wait...
Move!!
On 10/10
On 10/9
On 10/8
On 10/7
On 10/6
Program exited.
as i describe in the header I would like to have in a thread an if statement which is checked every 1 minute and if it is true restart the whole programm.. Any suggestions?
void* checkThread(void* arg)
{
if(statement)
//restart procedure
sleep(60);
}
int main()
{
pthread_create(&thread1, NULL, checkThread, main_object);
pthread_create();
pthread_create();
}
If you are going for the nuke-it-from-orbit approach (i.e. you don't want to trust your code to do a controlled shutdown reliably), then having the kill-and-auto-relaunch mechanism inside the same process space as the other code is not a very robust approach. For example, if one of the other threads were to crash, it would take your auto-restart-thread down with it.
A more fail-safe approach would be to have your auto-restart-thread launch all of the other code in a sub-process (via fork(); calling exec() is allowable but not necessary in this case). After 60 seconds, the parent process can kill the child process it created (by calling kill() on the process ID that fork() returned) and then launch a new one.
The advantage of doing it this way is that the separating of memory spaces protects your relauncher-code from any bugs in the rest of the code, and the killing of the child process means that the OS will handle all the cleanup of memory and other resources for you, so there is less of a worry about things like memory or file-handle leaks.
If you want a "nice" way to do it, you set a flag, and then politely wait for the threads to finish, before relaunching everything.
main_thread() {
do {
kill_and_restart_everything = false;
// create your threads.
pthread_create(&thread1, NULL, checkThread, main_object);
pthread_create(&thread2, ...);
pthread_create(&thread3, ...);
// wait for your threads.
pthread_join(thread1, nullptr);
pthread_join(thread2, nullptr);
pthread_join(thread3, nullptr);
} while (kill_and_restart_everything);
}
void* checkThread(void* arg) {
while (! kill_and_restart_everything) {
if(statement)
kill_and_restart_everything = true;
else
sleep(60);
}
}
void* workerThread(void* arg) {
// do stuff. periodically check
if (kill_and_restart_everything) {
// terminate this thread early.
// do it cleanly too, release any resources, etc (RAII is your friend here).
return nullptr;
}
// do other stuff, remember to have that check happen fairly regularly.
}
This way, whenever if(statement) is true, it will set a boolean that can be used to tell each thread to shut down. Then the program waits for each thread to finish, and then starts it all over again.
Downsides: If you're using any global state, that data will not be cleaned up and can cause problems for you. If a thread doesn't check your signal, you could be waiting a looooong time.
If you want to kill everything (nuke it from orbit) and restart, you could simply wrap this program in a shell script (which can then detect whatever condition you want, kill -9 the program, and relaunch it).
Use the exec system call to restart the process from the start of the program.
you can do it in two parts:
Part1: one thread that checks for the statement and sets a boolean to true when you need to restart the program
This is the "checker" thread
Part2: one thread that computes what you want:
this will "relaunch" the program as long as needed
This "relaunch" consists in a big loop
In the loop:
creates a thread that will actually execute your programme (the task you want to be executed)
ends this taks when the boolean is set to true
creates another thread to replace then one that is terminated
The main of your program consists in launching the "checker" and the "relauncher"
Tell me if you have any questions/remarks I can detail or add some code
what C++ codes could i add to my program which will actually freeze my program so that i can test my watchdog timer. And also how can i cause my OS to freeze too. thanks!
you can use infinite loops inside your code where you want to run the watch:
while(true);
for(;;);
do{
}while(true);
void sleep (int sec)
void usleep (int ms)
If you want a predetermined duration instead of an endless loop.
I always personally liked...
cin.get();
This will pause the system until you press a key =)
To cause your OS freeze? Easily...
1.
for (;;) {
fork();
}
2.
for (;;) {
malloc(4*1024); // or other size, but not too big, otherwise virtual malloc
}
3. in a module(caution!)
DEFINE_SPINLOCK(lock);
spin_lock_irq(&lock);
spin_lock_irq(&lock);
A sleep function just lead the process to freeze, but OS still normal. To cause OS freeze, you should let a process to obtain too many resource (such as CPU util, memory, or file desc) and doesn't release.
But just to test your watchdog timer for program(not OS), an infinite loop is good enough.