Instead of copying code, I would like to call to another function.
There are two functions, the one function, GetSlaves() returns with a number of slaves found during a scan.
Thing is, I suspect sometimes the returned value is incorrect, while a slave is down or stuck. Therefore I would like to run the GetSlaves function again if I am not happy with the number of slaves found. Please see the code below, questions follow.
SetSlaves(slaves)
{
if (slaves<3 || slaves>6) // I expect 4 or 6 to be found
{
for (tmp2 = 0; tmp2<3; tmp2++) // Try 3 times
{
GetSlaves(); // This function will scan for new slaves and then call SetSlaves(slaves);
}
}
else
{
WriteFlash(VMSSlaves,slaves); // I am happy with what was found, Sets the number of slaves found
}
}
My Question is, when the primary function is called again from the For statement, will it update the slaves variable (for instance a 4 is returned) and exit the IF and thus also the FOR..
Or, will the loop be endless if a slave is down and the two functions will call each other endlessly?
There are some serious control problems here and it may loop forever: when SetSlaves is called with a number of slaves, and the number is not to your liking, GetSlaves is called, which calls SetSlaves. Even if the number is to your liking, it will return, only to be in the loop of tmp2, calling GetSlaves which calls SetSlaves again. If now the number is not to your liking, the whole process repeats and can repeat indefinitly. And note that this is an indirect form of recursion.
My advice would be to have GetSlaves return the number of slaves and that the caller decides whether to call SetSlaves, and not have GetSlaves call SetSlaves.
You are correct. The loop would be endless if the if condition is satisfied and it enters the for loop.
In my opinion, the structure of the code is a bit iffy. I would rather have getslaves just get me number of slaves, and not call setslaves.
I'm writing an user-space program, in which I want to "block" a thread at some time. If I use mutex like function, the thread would be switched out of the processor. What I want is to let the thread keep on the proccessor without context switch invovled in a low power status or loop nop operations. And at some time, another thread could "wake" it up or "unblock" from the nop or low power status and continue execution. Is there any function or lib I can use?
It's good and valid question. Spin-loops like what you describe can use pause instruction in order to enable paired hyper-thread with more resources and enable power-saving optimizations.
E.g.
while(condition) _mm_pause();
If evaluating the condition consumes more resources than necessary, repeat the pause several times. E.g. tbb::spin_mutex uses a backoff algorithm where each failed condition check leads to doubling the number of pause iterations before the next evaluation.
See also this blog.
What purpose does while(1); serve ? I am aware while(1) (no semicolon) loops infinitely and is similar to a spinlock situation. However I do not see where while(1); could be used ?
Sample code
if(!condition)
{
while(1);
}
Note: This is not a case of do-while() or plain while(1).
Please note that all valid statements of the language do not have to serve a purpose. They are valid per the grammar of the language.
One can build many similar "useless" statements, such as if (1);.
I see such statements as the conjunction of a conditional (if, while, etc.) and the empty statement ; (which is also a valid statement although it obviously serves no specific purpose).
That being said, I encountered while (1); in security code. When the user does something very bad with an embedded device, it can be good to block them from trying anything else.
With while (1);, we can unconditionally block a device until an accredited operator manually reboots it.
while(1); can also be part of the implementation of a kernel panic, although a for(;;) {} loop seems to be a more common way of expressing the infinite loop, and there might be a non-empty body (for instance to panic_blink()).
If you dig down to assembly,
(this is easier to grasp from an embedded systems point of view, or if you tried to program a bootloader)
you will realize that a while loop is just a jmp instruction ... ie
(pseudo code: starting loop address)
add ax, bx
add ax, cx
cmp ax, dx
jz (pseudo code: another address location)
jmp (pseudo code: starting loop address)
Lets explain how this works, the processor will keep executing instructions sequentially ... no matter what. So the moment it enters this loop it will add register bx to ax and store in ax, add register cx to ax and store to ax, cmp ax, dx (this means subtract dx from ax) the jz instruction means jump to (another address location) if the zero flag is set (which is a bit in the flag register that will be set if the result of the above subtraction is zero), then jmp to starting loop address (pretty straight forward) and redo the whole thing.
The reason I bothered you with all this assembly is to show you that this would translate in C to
int A,B,C,D;
// initialize to what ever;
while(true)
{
A = A + B;
A = A + C;
if((A-D)==0)
{break;}
}
// if((X-Y)==0){break;} is the
// cmp ax, dx
// jz (pseudo code: another address location)
So imagine the senario in assembly if you just had a very long list of instructions that didn't end with a jmp (the while loop) to repeat some section or load a new program or do something ...
Eventually the processor will reach the last instruction and then load the following instruction to find nothing (it will then freeze or triple fault or something).
That is exactly why, when you want the program to do nothing until an event is triggered, you have to use a while(1) loop, so that the processor keeps jumping in its place and not reach that empty instruction address. When the event is triggered, it jumps to the event handler instructions address, executes it, clears the interrupt and goes back to your while(1) loop just jumping in its place awaiting further interrupts. Btw the while(1) is called a superloop if you want to read more about it ... Just for whoever that is insanely itching to argue and comment negatively at this point, this is not an assembly tutorial or a lecture or anything. It's just plain English explanation that is as simple as possible, overlooking a lot of underlying details like pointers and stacks and whatnot and at some instance over simplifying things to get a point across. No one is looking for documentation accuracy over here and I know this C code won't compile like this, but this is only for Demo !!
This is tagged C, but I'll start with a C++ perspective. In C++11, the compiler is free to optimize while(1); away.
From the C++11 draft standard n3092, section 6.5 paragraph 5 (emphasis mine):
A loop that, outside of the for-init-statement in the case of a for statement,
— makes no calls to library I/O functions, and
— does not access or modify volatile objects, and
— performs no synchronization operations (1.10) or atomic operations (Clause 29)
may be assumed by the implementation to terminate. [Note: This is intended to allow compiler transformations, such as removal of empty loops, even when termination cannot be proven. — end note ]
The C11 standard has a similar entry, but with one key difference. From the C11 draft standard n1570, (emphasis mine):
An iteration statement whose controlling expression is not a constant expression,156) that performs no input/output operations, does not access volatile objects, and performs no synchronization or atomic operations in its body, controlling expression, or (in the case of a for statement) its expression-3, may be assumed by the implementation to terminate.157)
156) An omitted controlling expression is replaced by a nonzero constant, which is a constant expression.
157) This is intended to allow compiler transformations such as removal of empty loops even when termination cannot be proven.
This means while(1); can be assumed to terminate in C++11 but not in C11. Even with that, note 157 (not binding) is interpreted by some vendors as allowing them to remove that empty loop. The difference between while(1); in C++11 and C11 is that of defined versus undefined behavior. Because the loop is empty it can be deleted in C++11. In C11, while(1); is provably non-terminating, and that is undefined behavior. Since the programmer has invoked UB, the compiler is free to do anything, including deleting that offending loop.
There have been a number of stackoverflow discussions on optimizing compilers deleting while(1);. For example, Are compilers allowed to eliminate infinite loops?, Will an empty for loop used as a sleep be optimized away?, Optimizing away a "while(1);" in C++0x. Note that the first two were C-specific.
An usage on embedded software is to implement a software reset using the watchdog:
while (1);
or equivalent but safer as it makes the intent more clear:
do { /* nothing, let's the dog bite */ } while (1);
If the watchdog is enabled and is not acknowledged after x milliseconds we know it will reset the processor so use this to implement a software reset.
I assume that the while(1); is not associated with a do loop...
The only semi-useful implementation of while(1); I have seen is a do-nothing loop waiting for an interrupt; such as a parent process waiting for a SIGCHLD, indicating a child process has terminated. The parent's SIGCHLD handler, after all child processes have terminated, can terminate the parent thread.
It does the trick, but wastes a lot of CPU-time. Such a usage should perhaps perform some sort of sleep to relinquish the processor periodically.
One place that I have seen a while(1); is in embedded programming.
The architecture used a main thread to monitor events and worker threads to handle them. There was a hardware watchdog timer (explanation here) that would perform a soft reset of the module after a period of time. Within the main thread polling loop, it would reset this timer. If the main thread detected an unrecoverable error, a while(1); would be used to tie up the main thread, thus triggering the watchdog reset. I believe that assert failure was implemented with a while(1); as well.
As others have said, it's just an infinite loop that does nothing, completely analogous to
while (1) {
/* Do nothing */
}
The loop with the semicolon does have a body. When used as a statement, a single semicolon is a null statement, and the loop body consists of that null statement.
For readability, to make it plain to the reader that the null statement is the body of the loop, I recommend writing it on a separate line:
while (1)
;
Otherwise it is easy to miss it at the end of the "while" line, where there usually isn't a semicolon, and the reader can mistake the next line as the body of the loop.
Or use an empty compound statement instead.
while(1);
is actually very useful. Especially when it's a program that has some sort of passcode or so and you want to disable the use of the program for the user because, for an example, he entered the wrong passcode for 3 times. Using a while(1); would stop the program's progress and nothing would happen until the program is rebooted, mostly for security reasons.
This may be used to wait for Interrupt. Basically you initialize all things you need and start waiting for some thing to occur. After that some specific function is called and executed, after that it goes back to waiting state.
That thing could be button pressed, mouse click/move, data received and etc.
What is more I would say, similar stuff is really often used by UI frameworks. While it waits for signals about user actions.
In AVR chipsets programming (using C programming language) this statement is frequently used, It plays a role like event loop.
Suppose I want to design a count-up counter, So I can use this code for implementing it:
void interrupt0() {
/* check if key pressed, count up the counter */
}
void main() {
/* Common inits */
/* Enable interrupt capability and register its routine */
/* Event loop */
while(1);
}
I think that the reason that while(1); is used is because earlier in the code an EventHandler or interrupt has been set on this thread. Using standard Thread Safe locking code can be fairly costly (in time) when you know that your code will only 'wait' for a very short amount of time.
Therefore you can set up the interrupt and 'spin' using while(1); which, although is a Busy Wait (doesn't let the CPU Idle/service other threads) takes up very few cycles to set up.
In summary, it's a 'cheap' spinlock while your thread waits for an interrupt or Event.
Since the condition is always true, we can say that we are using a logic tautology as known in mathematics.
While the loop proofs to be always true it won´t stop looping unless forced by the code or until resources have collapsed.
I have a while loop implemented in C for an MSP430 processor that currently looks like this:
register unsigned int sw_loop_count = 0U;
...
while (TACCL0 & CCIE)
{
++sw_loop_count;
}
...
#pragma vector=TIMERA0_VECTOR
__interrupt void Timer_A(void)
{
// Disable the timer interrupt flag and enable.
TACCTL0 &= ~CCIFG;
TACCTL0 &= ~CCIE;
}
I'm using this loop for calibration purposes, the context of which I don't think matters too much for my question. I've calculated that each iteration of the loop, including the check TACCL0 & CCIE takes 11 clock cycles. For purposes of granularity, I would really like to get this number as low as possible, and programmatically if possible. I might be being a complete moron, but I can't think of a way of reducing the cycle count for the loop, so any advice would be appreciated. I need the sw_loop_count value, one way or another.
Hmm, after I put a comment I realized that there may be something you can do ;-) In your while() condition you are checking two values. From the looks of it both those values must be defined as volatile so that they are ready from memory every single time they are used...
Can you reduce those two into a single one? Have your interrupt handler do the necessary comparison and set a single flag that you will be checking in your loop.
Or you can get really fancy and do it another way around, like that:
// signed and global (or you can pass it's address into your interrupt's routine)
volatile signed int sw_loop_count = 0;
Then there's your "measurement" loop:
while(++sw_loop_count) {}
and in your interrupt routine:
if(TACCL0 & CCIE)
{
real_count = sw_loop_count; // save the value for future use before we destroy it
sw_loop_count = -1; // this will turn into 0 in that while's pre-increment, ending the loop
}
OTOH... introducing the volatile may get so much hit from memory access that it may in fact slow down the while() loop. It really does all depend on your actual architecture (down to what type of memory controller and cache controllers there are) and I still maintain that you may be better off running it through an assembler mode and looking at what the compiler is doing.
I'm taking a university course to learn digital design using VHDL, and was doing some reading in the book the other day where I came across the following piece of code:
architecture abstract of computer_system is
...
cpu : process is
variable instr_reg : word;
variable PC : natural;
...
begin
loop
address <= PC;
mem_read <= '1';
wait until mem_ready;
...
end loop;
end process cpu;
end architecture abstract;
Now, as I've understood it, once a process reaches its last statement, it will go back and execute the first statement (provided that the last statement wasn't a wait, of course). And the purpose of loop ... end loop; is to repeat the intermediate code indefinitely. So doesn't that make the loop redundant in this case? Does it add any extra behaviour that isn't already exhibited by the process?
You're spot on as far as I can see, no need to have a loop in there.