Hello, I started studying BACI recently and I am having some trouble with monitors.
I know this is not strictly C/C++ but I did not know where to post this. I hope someone can help.
I made a very simple application that shows what my problem is:
[code]
monitor monSimple
{
int variable;
void method1()
{
cout << "method1: variable = " << variable << endl;
variable++;
cout << "method1: variable = " << variable << endl;
}
void method2()
{
cout << "method2: variable = " << variable << endl;
variable++;
cout << "method2: variable = " << variable << endl;
}
init
{
variable = 0;
}
} //monitor
main()
{
cobegin
{
method1();
method2();
}
} // main
[/code]
I expect the output to be:
method1: variable = 0
method1: variable = 1
method2: variable = 1
method2: variable = 2
or
method2: variable = 0
method2: variable = 1
method1: variable = 1
method1: variable = 2.
However, the real output is either:
method1: variable = 0
method1: variable = 2407
method2: variable = 0
method2: variable = 2607
or:
method2: variable = 0
method2: variable = 2607
method1: variable = 0
method1: variable = 2407.
What am I doing wrong?
Comments
In case it helps, if the main is changed from:
[code]
main()
{
cobegin
{
method1();
method2();
}
} // main
[/code]
to:
[code]
main()
{
method1();
method2();
} // main
[/code]
Then it outputs the 'expected' result (and the value in the init block initializes the variable properly in this case). I think this proves the monitor's code right. There could be some interference between cobegin and monitor.
A monitor is a block so that functions on it will only execute one at a time, basically. Ideal for mutual exclusion problems.
A cobegin a block whose functions will be executed concurrently. For example, you don't know which of the functions will be executed first.
Calling monitor functions inside a cobegin block, I am just trying to make a program where any of the monitor functions may be called first, but only one is running at a time.
[code]
monitor monSimple
{
int variable;
void method1()
{
cout << "method1: variable = " << variable << endl;
variable++;
cout << "method1: variable = " << variable << endl;
}
void method2()
{
cout << "method2: variable = " << variable << endl;
variable++;
cout << "method2: variable = " << variable << endl;
}
init
{
variable = 0;
}
} //monitor
void method1aux()
{
method1();
}
void method2aux()
{
method2();
}
main()
{
cobegin
{
method1aux();
method2aux();
}
} // main[/code]
Apparently you can't call monitor functions directly from inside a cobegin block (which is something I found by trial and error, it's not in the documentation as far as I can see). So I just enclosed the calls in auxiliary functions and it works.