Why is this code no solution to the critical section problem? - process

I'm trying to understand process synchronisation and have been thinking the past couple of hours about this piece of code and why it is not a suitable solution to the critical section problem. My take on this problem would be that Progress is not fullfilled since turn can be only modified inside of the first inner while loop but I am not quite sure about that.
I would be really thankful for any thougts and tips regarding this matter.
// initialised with FALSE.
boolean flag [2];
// With values 0, 1. Any initialisation.
int turn;
while TRUE {
flag [i] = TRUE ;
while ( turn != i) {
while ( flag [j]) {
noop ;
}
turn =i;
}
criticalSection (Pi);
flag [i] = FALSE ;
remainderSection (Pi);
}

Related

Variable getting overwritten in for loop

In a for loop, a different variable is assigned a value. The variable which has already been assigned a value is getting assigned the value from next iteration. At the end, both variable have the same value.
The code is for validating data in a file. When I print the values, it prints correct value for first iteration but in the next iteration, the value assigned in first iteration is changed.
When I print the value of $value3 and $value4 in the for loop, it shows null for $value4 and some value for $value3 but in the next iteration, the value of $value3 is overwritten by the value of $value4
I have tried on rakudo perl 6.c
my $fh= $!FileName.IO.open;
my $fileObject = FileValidation.new( file => $fh );
for (3,4).list {
put "Iteration: ", $_;
if ($_ == 4) {
$value4 := $fileObject.FileValidationFunction(%.ValidationRules{4}<ValidationFunction>, %.ValidationRules{4}<Arguments>);
}
if ($_ == 3) {
$value3 := $fileObject.FileValidationFunction(%.ValidationRules{3}<ValidationFunction>, %.ValidationRules{3}<Arguments>);
}
$fh.seek: SeekFromBeginning;
}
TL;DR It's not possible to confidently answer your question as it stands. This is a nanswer -- an answer in the sense I'm writing it as one but also quite possibly not an answer in the sense of helping you fix your problem.
Is it is rw? A first look.
The is rw trait on a routine or class attribute means it returns a container that contains a value rather than just returning a value.
If you then alias that container then you can get the behavior you've described.
For example:
my $foo;
sub bar is rw { $foo = rand }
my ($value3, $value4);
$value3 := bar;
.say for $value3, $value4;
$value4 := bar;
.say for $value3, $value4;
displays:
0.14168492246366005
(Any)
0.31843665763839857
0.31843665763839857
This isn't a bug in the language or compiler. It's just P6 code doing what it's supposed to do.
A longer version of the same thing
Perhaps the above is so far from your code it's disorienting. So here's the same thing wrapped in something like the code you provided.
spurt 'junk', 'junk';
class FileValidation {
has $.file;
has $!foo;
method FileValidationFunction ($,$) is rw { $!foo = rand }
}
class bar {
has $!FileName = 'junk';
has %.ValidationRules =
{ 3 => { ValidationFunction => {;}, Arguments => () },
4 => { ValidationFunction => {;}, Arguments => () } }
my ($value3, $value4);
method baz {
my $fh= $!FileName.IO.open;
my $fileObject = FileValidation.new( file => $fh );
my ($value3, $value4);
for (3,4).list {
put "Iteration: ", $_;
if ($_ == 4) {
$value4 := $fileObject.FileValidationFunction(
%.ValidationRules{4}<ValidationFunction>, %.ValidationRules{4}<Arguments>);
}
if ($_ == 3) {
$value3 := $fileObject.FileValidationFunction(
%.ValidationRules{3}<ValidationFunction>, %.ValidationRules{3}<Arguments>);
}
$fh.seek: SeekFromBeginning;
.say for $value3, $value4
}
}
}
bar.new.baz
This outputs:
Iteration: 3
0.5779679442816953
(Any)
Iteration: 4
0.8650280000277686
0.8650280000277686
Is it is rw? A second look.
Brad and I came up with essentially the same answer (at the same time; I was a minute ahead of Brad but who's counting? I mean besides me? :)) but Brad nicely nails the fix:
One way to avoid aliasing a container is to just use =.
(This is no doubt also why #ElizabethMattijsen++ asked about trying = instead of :=.)
You've commented that changing from := to = made no difference.
But presumably you didn't change from := to = throughout your entire codebase but rather just (the equivalent of) the two in the code you've shared.
So perhaps the problem can still be fixed by switching from := to =, but in some of your code elsewhere. (That said, don't just globally replace := with =. Instead, make sure you understand their difference and then change them as appropriate. You've got a test suite, right? ;))
How to move forward if you're still stuck
Right now your question has received several upvotes and no downvotes and you've got two answers (that point to the same problem).
But maybe our answers aren't good enough.
If so...
The addition of the reddit comment, and trying = instead of :=, and trying the latest compiler, and commenting on those things, leaves me glad I didn't downvote your question, but I haven't upvoted it yet and there's a reason for that. It's because your question is still missing a Minimal Reproducible Example.
You responded to my suggestion about producing an MRE with:
The problem is that I am not able to replicate this in a simpler environment
I presumed that's your situation, but as you can imagine, that means we can't confidently replicate it at all. That may be the way you prefer to go for reasons but it goes against SO guidance (in the link above) and if the current answers aren't adequate then the sensible way forward is for you to do what it takes to share code that reproduces your problem.
If it's large, please don't just paste it into your question but instead link to it. Perhaps you can set it up on glot.io using the + button to use multiple files (up to 6 I think, plus there's a standard input too). If not, perhaps gist it via, say, gist.github.com, and if I can I'll set it up on glot.io for you.
What is probably happening is that you are returning a container rather than a value, then aliasing the container to a variable.
class Foo {
has $.a is rw;
}
my $o = Foo.new( a => 1 );
my $old := $o.a;
say $old; # 1
$o.a = 2;
say $old; # 2
One way to avoid aliasing a container is to just use =.
my $old = $o.a;
say $old; # 1
$o.a = 2;
say $old; # 1
You could also decontainerize the value using either .self or .<>
my $old := $o.a.<>;
say $old; # 1
$o.a = 2;
say $old; # 1
(Note that .<> above could be .self or just <>.)

Selection a bool through randomizer

I have a total of 6 booleans and the only thing separating them is a number. They're named checker0 though 5.
So checker0, checker1, checker2, checker3, checker4 and checker5.
All of these grants or denies access to certain parts of the app wether the bool is true or false.
I then have a randomiser using:
randomQuestionNumber = arc4random_uniform(5);
So say we get number 3, checker3 = true;
But my question now is would it be possible to set this one to true without having to go thru if statements.
My idea was to implement the way you print a int to say the NSLog using the %d.
NSLog(#"The number is: %d", randomQuestionNumber);
So something like:
checker%d, randomQuestionNumber = true.
Would something like that be possible? So i won't have to do like this:
if (randomQuestionNumber == 0) {
checker0 = true;
}
else if (randomQuestionNumber == 1)
{
checker1 = true;
}
Thanks you very much! :)
Every time you find yourself in a situation when you name three or more variables checkerN you know with a high degree of probability that you've missed a place in code where you should have declared an array. This becomes especially apparent when you need to choose one of N based on an integer index.
The best solution would be to change the declaration to checker[6], and using an index instead of changing the name. If this is not possible for some reason, you could still make an array of pointers, and use it to make modifications to your values, like this:
BOOL *ptrChecker[] = {&checker0, &checker1, &checker2, ...};
...
*ptrChecker[randomQuestionNumber] = true;

Counter as variable in for-in-loops

When normally using a for-in-loop, the counter (in this case number) is a constant in each iteration:
for number in 1...10 {
// do something
}
This means I cannot change number in the loop:
for number in 1...10 {
if number == 5 {
++number
}
}
// doesn't compile, since the prefix operator '++' can't be performed on the constant 'number'
Is there a way to declare number as a variable, without declaring it before the loop, or using a normal for-loop (with initialization, condition and increment)?
To understand why i can’t be mutable involves knowing what for…in is shorthand for. for i in 0..<10 is expanded by the compiler to the following:
var g = (0..<10).generate()
while let i = g.next() {
// use i
}
Every time around the loop, i is a freshly declared variable, the value of unwrapping the next result from calling next on the generator.
Now, that while can be written like this:
while var i = g.next() {
// here you _can_ increment i:
if i == 5 { ++i }
}
but of course, it wouldn’t help – g.next() is still going to generate a 5 next time around the loop. The increment in the body was pointless.
Presumably for this reason, for…in doesn’t support the same var syntax for declaring it’s loop counter – it would be very confusing if you didn’t realize how it worked.
(unlike with where, where you can see what is going on – the var functionality is occasionally useful, similarly to how func f(var i) can be).
If what you want is to skip certain iterations of the loop, your better bet (without resorting to C-style for or while) is to use a generator that skips the relevant values:
// iterate over every other integer
for i in 0.stride(to: 10, by: 2) { print(i) }
// skip a specific number
for i in (0..<10).filter({ $0 != 5 }) { print(i) }
let a = ["one","two","three","four"]
// ok so this one’s a bit convoluted...
let everyOther = a.enumerate().filter { $0.0 % 2 == 0 }.map { $0.1 }.lazy
for s in everyOther {
print(s)
}
The answer is "no", and that's a good thing. Otherwise, a grossly confusing behavior like this would be possible:
for number in 1...10 {
if number == 5 {
// This does not work
number = 5000
}
println(number)
}
Imagine the confusion of someone looking at the number 5000 in the output of a loop that is supposedly bound to a range of 1 though 10, inclusive.
Moreover, what would Swift pick as the next value of 5000? Should it stop? Should it continue to the next number in the range before the assignment? Should it throw an exception on out-of-range assignment? All three choices have some validity to them, so there is no clear winner.
To avoid situations like that, Swift designers made loop variables in range loops immutable.
Update Swift 5
for var i in 0...10 {
print(i)
i+=1
}

C++ decrement vector cycle

I have a separate stack in my program with this timer vector attached. When called, the stack pops an element out and the timer keeps track of how long it is out via user input. When the time reaches 0, the element is put back into the stack. I wanted to work through multiple timers so I tried to put them all into a vector and have them all decrement by one time unit when a function is called. Not totally clear on how vectors work so I do not know how to decrement all of a vector's values.
int wait(vector<int> &x){
std::vector<int>::iterator itr;
for(itr = x.begin(); itr < x.end(); itr++)
{ //psuedocode
//x[itr]--;
}
}
I just want to make sure I'm going in the right direction.
Here is how you can decrement all the values in the vector
int wait(vector<int> &x){
for(std::vector<int>::iterator itr = x.begin(); itr != x.end(); itr++)
{
(*itr)--;
}
}
or using C++11
int wait(vector<int> x){
for (int& i : x )
i--;
}
To decrease the value pointed by the iterator in the code, you can do -
for(itr = x.begin(); itr < x.end(); itr++)
{ //psuedocode
(*itr)--;
}
*itr returns the value being pointed by the iterator.

integer that becomes 0 in a strange way

I have an integer : (using xcode for iPhone ) .
int wordCounter=1;
Later on, when i fill arrays with it-as a pointer,in a for loop, it somehow becomes 0 after it becomes a certain number . i have checked my program many times for bugs, and i realize that i dont even have a decrement on it anywhere . i do have wordCounter++.
Now i have seen that i have many lines like this,that after them it becomes 0 :
if(tempBinary[countWords-1][j] != tempBinary[countWords][j])
so i was thinking that countWords-1 decrement it down again and again, is that possible?
i dont have any other decrement or initialization on this variable in my whole program.
i COULD see that when the tempBinary defined as size 7, it initialize at 5, and if tempBinary is 5, it zeroing on 3 ..
is it possible that the array is overflow and is zeroing it? i dont think so..
whats wrong here ?
thanks .
EDIT (one of the problematic states)
int countWords=1;
int stabilityK=0;
tempBinary[0][0]= tempBinary[0][1]=tempBinary[0][2]=tempBinary[0][3]=tempBinary[0][4]=tempBinary[0][5]=tempBinary[0][6]=tempBinary[0][7]=1 ;
for(int k=0;k<numOfBuffers;k++)
{
NSLog(#"countwords:%d",countWords-1);
float *temp=getFFT(buffersRing[k],buffersRing[k][0]);
for(int j=0;j<wordSize;j++)
{
switch(state_on_signal)
{
case WAIT_FOR_SECOND_CHANGE:
//get new word
if(temp[goodBins[j]] > decisionLine[j])
tempBinary[countWords][j]=1;
else
tempBinary[countWords][j]=0;
if(tempBinary[countWords-1][j] != tempBinary[countWords][j])
newData=1;
NSLog(#"s1: countwords:%d",countWords-1);
if(j==wordSize-1)
{
NSLog(#"s2: countwords:%d",countWords-1);
NSLog(#"PRE TEMP:%d%d%d%d%d%d%d%d",tempBinary[countWords-1][0],tempBinary[countWords-1][1],tempBinary[countWords-1][2],tempBinary[countWords-1][3],tempBinary[countWords-1][4],tempBinary[countWords-1][5],tempBinary[countWords-1][6],tempBinary[countWords-1][7] );
NSLog(#"NEW TEMP-WAIT FOR SECOND CHANGE :%d%d%d%d%d%d%d%d",tempBinary[countWords][0],tempBinary[countWords][1],tempBinary[countWords][2],tempBinary[countWords][3],tempBinary[countWords][4],tempBinary[countWords][5],tempBinary[countWords][6],tempBinary[countWords][7] );
NSLog(#"s3: countwords:%d",countWords-1);
//TAKE NEW DATA
if(newData==1)
{
NSLog(#" TOOK new BINARY at current k:%d, so took data at: %d",k,(k+markedK)/2);
for(int s=0;s<wordSize;s++)
{
if( getFFT(buffersRing[(k+markedK)/2],buffersRing[(k+markedK)/2][0])[goodBins[s] ] >decisionLine[s] )
binary[countWords-1][s]= 1;
else
binary[countWords-1][s]= 0;
}
NSLog(#"s4: countwords:%d",countWords-1);
NSLog(#"BINARY%d: %d%d%d%d%d%d%d%d :%d",(countWords-1), binary[(countWords-1)][0], binary[(countWords-1)][1], binary[(countWords-1)][2], binary[(countWords-1)][3], binary[(countWords-1)][4], binary[(countWords-1)][5], binary[(countWords-1)][6], binary[(countWords-1)][7],[self getDecimal:binary[countWords-1]]);
countWords++;
markedK=k;
state_on_signal=WAIT_FOR_STABILITY;
}
newData=0;
}
break;
so i was thinking that countWords-1 decrement it down again and again,
is that possible?
No
Usually this happens when you misuse a pointer and write a value to the wrong address in memory.
For example: where and how is declared tempBinary ?
As it's not possible (at least for me) to see the problem just looking at your code I'd suggest to step through your code with the debugger and see when countWords gets changed. Here lies the problem (at least one of them).