Click here to Skip to main content
16,022,339 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C++
/*

 Add 10 to a variable in each of two processes.

 The answer can be between 2 and 20.

 Local variable enables bad scenario with source-level interleaving.

*/

int sum = 0;

void add10() {
	int i;
	int local;
	for (i = 1; i <= 10;i++)
 {
		local = sum;
		sum = local + 1;
}
}

void main() {
	cobegin { 
		add10(); 
                add10();
        }
        cout << "Sum = " << sum << endl;
}


.....................................................
I use jbaci(is a program that run functioد that are in "cobegin" coincidence

but each time that I run this I see different results between 0. and 20

I dont know how to solve this prob with semaphore or other method

please help me

thank you for decision for solve this
Posted
Updated 30-Oct-10 21:32pm
v6
Comments
Dalek Dave 30-Oct-10 17:59pm    
Edited for Grammar and Readability.

I have not used jbaci, but assuming it's some kind of parallel environment/library, you need to make sure you only let one thread write to sum (via some kind of synchronized block, jbaci should have one I assume).

See http://www.codeproject.com/KB/threads/lwsync.aspx[^]
 
Share this answer
 
v2
Comments
Dalek Dave 30-Oct-10 17:59pm    
Good old CP Archives!
/* Add 10 to a variable in each of two processes.
The answer can be between 2 and 20.
Local variable enables bad scenario with source-level interleaving.
*/



int sum = 0;

int i;
int local;
semaphore w=1;

void add10(int f)
{



wait(w);

for(i=1;i<=10;i++){local=sum;sum=local+1;}

signal(w);



}

void main() {
cobegin {
add10(0);
add10(1);
}
cout << "Sum = " << sum << endl;
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900