/* ECE 462 Object-Oriented Programming using C++ and Java by Yung-Hsiang Lu, Purdue University This program uses two methods to accumulate numbers. The purpose is to find the total when each thread increments NUMBER_ITERATION times to the shared (static) attribute "total". Unfortunately, neither method always produces the correct result. SyncAlways is more likely to produce a wrong result but SyncLast may also prodcue a wrong result occasionally. In this lab exercise, you need to convert this Java program to a correct C++ program using multiple threads. Your submission needs to include two files: 1. README: explains the problems in this Java program and how you fix the problems in your C++ program. 2. C++ program: implements correct synchronization. The C++ program must keep the same structure as in this Java program: multiple threads increment a shared attribute (or object). The C++ program *CANNOT* output the result of NUMBER_ITERATION * NUMBER_THREAD directly. Please use one of the qstructxx.ecn.purdue.edu machines. Each has 2 quad-core processors. */ import java.util.*; class SyncAlways extends Thread { public static long total = 0; public static long NUMBER_ITERATION; synchronized public void addTotal() { total ++; } public void run() { for (long iter = 0; iter < NUMBER_ITERATION; iter ++) { addTotal(); } } public SyncAlways(long ITERATION) { NUMBER_ITERATION = ITERATION; } public String toString() { return new String("Total = " + total); } } class SyncLast extends Thread { public static long total = 0; public static long NUMBER_ITERATION; private long subtotal = 0; synchronized public void addTotal(long sub) { total += sub; } public void run() { for (long iter = 0; iter < NUMBER_ITERATION; iter ++) { subtotal ++; } addTotal(subtotal); } public SyncLast(long ITERATION) { NUMBER_ITERATION = ITERATION; } public String toString() { return new String("Total = " + total); } } class lab08code { public static void main( String[] args ) { long NUMBER_ITERATION = 1000000; int NUMBER_THREAD = 8; System.out.println("Iteration = " + NUMBER_ITERATION / 100000 + " (millions) " + "Thread = " + NUMBER_THREAD); SyncLast [] slt = new SyncLast[NUMBER_THREAD]; for (int tcnt = 0; tcnt < NUMBER_THREAD; tcnt ++) { slt[tcnt] = new SyncLast(NUMBER_ITERATION); } try { for (int tcnt = 0; tcnt < NUMBER_THREAD; tcnt ++) { slt[tcnt].start(); } for (int tcnt = 0; tcnt < NUMBER_THREAD; tcnt ++) { slt[tcnt].join(); } } catch (InterruptedException ie) { System.out.println("exception caught"); } SyncAlways [] saws = new SyncAlways[NUMBER_THREAD]; for (int tcnt = 0; tcnt < NUMBER_THREAD; tcnt ++) { saws[tcnt] = new SyncAlways(NUMBER_ITERATION); } try { for (int tcnt = 0; tcnt < NUMBER_THREAD; tcnt ++) { saws[tcnt].start(); } for (int tcnt = 0; tcnt < NUMBER_THREAD; tcnt ++) { saws[tcnt].join(); } } catch (InterruptedException ie) { System.out.println("exception caught"); } System.out.println("SyncAlways " + saws[0]); System.out.println("SyncLast " + slt[0]); } }