GQCS gets notification, when WSAsend returns 0? - send

Although I have read a lot about WSAsend (msdn), I still need some clarifications.
Part of my code:
int rc;
rc=WSASend(Socket,....);
if (rc==0) {....}
else if ((rc == SOCKET_ERROR) && (WSA_IO_PENDING != (err = WSAGetLastError())))
{
printf("WSASend failed with error: %d Socket(%d) \n", err,(pTmp1->Socket));
....
}
There is said in msdn that WSAsend operation may sometimes completes immediately returning zero (it never happened during my test server ). So if this happens, the GetQueuedCompletionStatus will get notification?
Thanks in advance.

If any socket API call which initiates an overlapped operation which will generate a completion to an I/O completion port when completed returns 0 then a completion IS generated and posted to the IOCP. See this Microsoft knowledge base article for details. Thus you need no special handling for the non error return case.
Except...
If you are using SetFileCompletionNotificationMode() to set the the FILE_SKIP_COMPLETION_PORT_ON_SUCCESS mode. In which case a return value of 0 does NOT cause normal completion handling and you need to do your completion handling after the successful API call.

Related

Why do I get “Lexical with name '$x' does not exist in this frame” when using “will leave”?

I have the following Raku code:
class Thing {
method close {
say "closed";
}
};
for 1..1000 {
my $x will leave { .close } = Thing.new;
}
Running it, I get the error:
Lexical with name '$x' does not exist in this frame
in block <unit> at c.raku line 7
Interestingly, this only happens if the number of iterations is high enough (with 500 or 100, I do not get any error messages).
If I change the body of the cycle to
my $x = Thing.new;
LEAVE $x.close;
then everything works without errors as well.
What is happening here? Did I misunderstand the will leave construct? (It seems to me the two versions should be equivalent.)
EDIT: Further observation – when running the code multiple times, the error appears nondeterministically. This suggests that the problem is somehow connected to garbage collection, but I am still confused as to what actually happens here.
I am using Rakudo v2021.03.
This is a bug. Have made an issue for it: https://github.com/rakudo/rakudo/issues/4403
I suggest using the workaround in the meantime.

Why should I use & in this syntax? Problem with SPI register

I'm writing a program for SPI communication betweend LPC2109/2 and MCP4921. This is an assignment
on studies. My tutor ask me a question why "&" is necessary in this line? In this line we wait for the end of SPI transmission. Which answer should be right?
#define SPI_SPIF_bm (1<<7)
...
while((S0SPSR & SPI_SPIF_bm) == 0){}
We use "&" as logic AND, for instance: (0000 & 1000) gives us 0000 instead of (0000 | 1000) gives us 1000.
Can I use only this line of code: while((S0SPSR) == 0){}? In my opinion - no. We need to compare value in register S0SPSR with bit SPIF SPI_SPIF_bm.
Is there maybe different solution?
Attachment
User Manual for LPC2129/01: https://www.nxp.com/docs/en/user-guide/UM10114.pdf
The SPI peripheral of LPC2109/2 sets different bits of S0SPSR depending on the actual event that happens which may depend on external circumstances. For example if there's a write collision on the SPI line it sets the WCOL bit instead of SPIF.
If you use while((S0SPSR) == 0){} it will wait until either a successful transaction or an error happens because it will exit the loop if any of the bits of S0SPSR is set.
while((S0SPSR & SPI_SPIF_bm) == 0){} only checks if the transaction has completed successfully. It is a good practice to check the error bits too because in case of an error you would stuck in this loop forever as SPIF is never goint to be set.
For a robust solution I would go with something like this:
while(S0SPSR == 0) {}
if (S0SPSR & SPI_SPIF_bm) { /* SPI_SPIF_bm remains set until data register has not been accessed */
/* Success, read the data register, return data, etc. */
} else {
/* Handle error */
}
If you are interested in the particular type of the error you need to store S0SPSR in a variable in each cycle as those bits are cleared on reading S0SPSR. Also you should to add a counter or a more sophisticated timeout solution to the loop to exit if none of the flags are sets in a reasonable period.
You might think these errors would never happen because you have a simple circuit but they do happen in real life and it's worth doing proper error handling.

Can the recordsToSave property of CKModifyRecordsOperation object be safely used in its modifyRecordsCompletionBlock

Suppose I start a saveOperation using a CKModifyRecordsOperation object. Can I safely assume that the recordsToSave of the object will store the list of records given at start when I access it within the modifyRecordsCompletionBlock that is executed after the operation completes.
I would assume so, but then I saw this line in the Apple doc (basically not sure what they mean by "initial": The initial contents of the array are set to the records you specified in the initWithRecordsToSave:recordIDsToDelete: method. You can modify this array as needed before executing the operation.
If there are rare circumstances where it can change, then I want to go another way in my retry logic.
EDIT added code
CKModifyRecordsOperation *saveOperation = [[CKModifyRecordsOperation alloc] initWithRecordsToSave:recordsToSave recordIDsToDelete:nil] ;
saveOperation.modifyRecordsCompletionBlock = completionBlock ; //see completion block definition below
[self.publicDatabase addOperation:saveOperation] ;
[self.OperationQ addObject: saveOperation] ; //Saved in Q for later retrieval
completionBlock is defined as
^(NSArray *savedRecords, NSArray *deletedRecordIDs, NSError * operationError){
if(operationError)
{
DDLogError(#"Save of Touch event records failed with error %#",operationError) ;
//Retry, can I do this and safely assume first record retrieved here is the first record I inserted into original recordsToSave array
CKRecord *cardinalRecord = self.OperationQ[0].recordsToSave[0] ;
//Read a field from it to decide how to handle retry (e.g: retry after delay if important set of records, don't retry if not etc)..
}
else
{
//Handle success case
}
}
Based on the code you added to the question, it seems that you wish to retrieve the array of records originally passed to the modification operation.
Accessing self.OperationQ[0].recordsToSave will certainly give you back the same array passed into [[CKModifyRecordsOperation alloc] initWithRecordsToSave:recordsToSave recordIDsToDelete:nil]
The message you reference from Apple's docs simply means that if your code updated the contents of recordsToSave, it is safe to make those changes up until you call addOperation:.
The operation won't ever change that array. So if you don't change it, then accessing it in the completion block will give you back exactly what you passed in originally.
In short No. The list of records you get at the end will be the ones that CloudKit has successfully updated. There is a possibility that it failed to update one or more in which case you need to take appropriate action.
Take a closer look at this apple documentation page https://developer.apple.com/library/ios/documentation/CloudKit/Reference/CloudKit_constants/index.html#//apple_ref/doc/constant_group/Record_Changed_Error_Keys
Which details the sort of scenarios that you need to think about.

In SPIN/Promela, how to receive a MSG from a channel in the correct way?

I read the spin guide yet there is no answer for the following question:
I have a line in my code as following:
Ch?x
where Ch is a channel and x is channel type (to receive MSG)
What happens if Ch is empty? will it wait for MSG to arrive or not?
Do i need to check first if Ch is not empty?
basically all I want is that if Ch is empty then wait till MSG arrives and when it's arrive continue...
Bottom line: the semantics of Promela guarantee your desired behaviour, namely, that the receive-operation blocks until a message can be received.
From the receive man page
EXECUTABILITY
The first and the third form of the statement, written with a single
question mark, are executable if the first message in the channel
matches the pattern from the receive statement.
This tells you when a receive-operation is executable.
The semantics of Promela then tells you why executability matters:
As long as there are executable transitions (corresponding to the
basic statements of Promela), the semantics engine will select one of
them at random and execute it.
Granted, the quote doesn't make it very explicit, but it means that a statement that is currently not executable will block the executing process until it becomes executable.
Here is a small program that demonstrates the behaviour of the receive-operation.
chan ch = [1] of {byte};
/* Must be a buffered channel. A non-buffered, i.e., rendezvous channel,
* won't work, because it won't be possible to execute the atomic block
* around ch ! 0 atomically since sending over a rendezvous channel blocks
* as well.
*/
short n = -1;
proctype sender() {
atomic {
ch ! 0;
n = n + 1;
}
}
proctype receiver() {
atomic {
ch ? 0;
n = -n;
}
}
init {
atomic {
run sender();
run receiver();
}
_nr_pr == 1;
assert n == 0;
/* Only true if both processes are executed and if sending happened
* before receiving.
*/
}
Yes, the current proctype will block until a message arrives on Ch. This behavior is described in the Promela Manual under the receive statement. [Because you are providing a variable x (as in Ch?x) any message in Ch will cause the statement to be executable. That is, the pattern matching aspect of receive does not apply.]

Understanding what Fault, Error and Failure mean

Consider the following class:
class Xyz {
public int count;
public void numZero (int[] x) {
// Effects: if x == null throw NullPointerException
// else return the number of occurrences of 0 in x
int count = 0;
for (int i = 1; i < x.length; i++) //we have a bug here
{
if (x[i] == 0)
{
count++;
}
}
this.count = count;
}
}
I'm trying to wrap my head about what Fault, Error and Failure really mean.
Fault
From what I've come to understand, a Fault in this context would be a flaw in the code's written logic.
So in this case the Fault would be the fact that the code instructs the computer to start iterating over all elements of v with a start index of 1 instead of the expected 0.
Error
When running the above method, we always get an Error but in once instance (when v.length == 0), as what we really want is to iterate over all elements of x, but since we're starting with i = 1, that is not really happening.
With an empty vector as input, as we don't enter the for loop, so our incorrect code isn't run, meaning that the Error doesn't happen, and everything happens as should in theory.
Failure
Since our code has a Fault that in execution-time will almost always manifest in a Error, we only have a Failure when we effectively see the incorrect output.
Assuming that an Error effectively happened in my program, we only have a Failure if it is in some way visible to the outside world. That is, had I private int count; instead of public int count; I'd never ever have an Error in my class (of course it'd be the most useless class ever!). Is this right?
Is everything I said correct or am I erring in something?
Thanks
Failure: A difference from the expected result. This is the problem
you observe.
Fault: The cause of the failure.
Error: The mistake which caused the fault to occur. e.g, typos.
An example of failure, fault and error.
pre: param is an integer.
post: returns the product of the param multiplied by 2.
1. int double (int param) {
2. int result;
3. result = param * param;
4. return result;
5. }
• A call to double(3) returns 9, but the post condition says it should return 6.
• Result 9 represents a failure.
• The failure is due to the fault at line 3, ( "* param" is used instead of "* 2")
• The error is a typo, ( someone typed "* param" instead of "* 2" by mistake).
Why give three different labels for a "Bug"?
They help communicate how precisely you know what the problem is.
Saying "failure" means you know something is wrong but don't know the cause.
Saying "fault" means you know the cause, but don't know why the fault occurred.
Saying "Error" means you know why the fault occurred; e.g.: The coder was distracted by a firetruck passing by.
You could ask, "But why did the person make a typo?" But that gets into into human factors and out of the scope of the question.
Source: Zhen Ming (Jack) Jiang - EECS 4413, Software Testing, York University.
First, a failure occurs whenever the actual service delivered by a system deviates from its expected service. Note that since even specifications can go wrong, the definition does not rely on them.
Second, an error is the part of the system state that may lead to a failure. The state of the system can go wrong but never reach the output, thus not lead to a failure.
Third, a fault is the cause of an error. It can be a design fault, a cosmic ray or whatever. If, as you point out, the fault is not activated, no error is produced.
Take a look at the basic concepts and terminology of dependability for more information.
Error is a deviation from the actual and the expected result. It represents the mistakes made by the people.
Faults are the result of an error. It is the incorrect step or process due to which the program or the software behaves in an unintended manner
Bug is an evidence of Fault in a program due to which program does not behave in an intended manner
Failure is an inability of the system or components to perform its required function. Failure occurs when Faults executes
Defect is said to be detected when Failure occurs.
There are a plurality of different definitions, the one I personally prefer is the following:
Fault -> Error -> Failure
Fault: The verified or hypothesized cause of an error (malfunctions, external interference, design errors).
Error: The manifestation of a fault within a program or data structure (difference between actual output and expected output).
Failure: The event that occurs when an error reaches the service interface, altering the service itself (leads to the inability of a system or component to perform required function according to its specification).
The Error in Error/Fault/Failure refers to the human error that introduced the problem. The human error was the incorrect thinking that caused the user to create an incorrect for statement in your example.
Errors are hard to measure or understand. It is difficult in many cases to know what the developer was thinking when the made the error that introduced the fault. That is why they like to differentiate between error and fault. We can see that there is a fault in the code, but it is hard to know why the error was created. It could be that the code was correct, and then during a subsequent change, the for loop was changed.
I always remember that an Error by a programmer leads to a fault in the code that results in a failure for the user. Not all errors result in a fault. Not all faults result in failures.
The software Fault refers to a bug in the code. And it is DURING the software activity.
While software Failure is when the system misbehaves. This is observed LATER than a fault.
Fault may be the cause for a Failure. Fault is "WHAT" and Failure is "WHEN".
Those are only fundamentals, but still I hope that it sheds some light on the matter.