## Study Guide 6

Code Jams are open book. 40 minutes in lab.

Topics:

Everything from Study Guide 5, plus

• mutex, barrier

## Practice questions

• What is a mutex? When do we need to use mutex?

• What is a race condition?

• What does it mean for a function to be thread safe?

• Why and when might we want to use multiple threads?

• When might we want to use multiple processes versus multiple threads?

1) Write a multi-threaded program (4 threads) that computes the average of a list of numbers. You can assume that the size of the list can be evenly divided by 4.

2) The following multi-threaded program simulates two bank accounts. But it’s not working correctly. What is going on and how can we fix it?

``````struct account {
int balance;
};

void *Transfer(void *args){
struct account** accounts = (struct account**) args;
struct account* fromAcct = accounts[FROM];
struct account* toAcct = accounts[TO];

for (int i = 0; i < 10000; i++) {

fromAcct->balance -= 25;
toAcct->balance += 25;

}

return NULL;
}

int main() {

// create accounts for A and B
struct account accountA;
struct account accountB;
accountA.balance = 100;
accountB.balance = 50;
printf("Starting balances:\n");
printf("\tA: %d\n", accountA.balance);
printf("\tB: %d\n", accountB.balance);

struct account* transformA2B;
transformA2B = &accountA;
transformA2B = &accountB;

struct account* transformB2A;
transformB2A = &accountB;
transformB2A = &accountA;

// wait for threads to finish

printf("Ending balances:\n");
printf("\tA: %d\n", accountA.balance);
printf("\tB: %d\n", accountB.balance);

// cleanup

return 0;
}``````

3) The following multi-threaded program attempts to count the numbers in a list that are greater than 1000 but isn’t working correctly. What is going on and how can we fix it?

``````#define SIZE 100000

static unsigned long long count = 0;
int start_index;
int end_index;
int* array;
};

void *countOver1000(void *userdata) {

for (int i = data->start_index; i < data->end_index; i++) {
if (data->array[i] > 1000) {
count++;
}
}
return (void*) NULL;
}

int main(int argc, char *argv[]) {
srand(time(0));

int values[SIZE];
unsigned long long test = 0;
for (int i = 0; i < SIZE; i++) {
values[i] = rand() % SIZE;
if (values[i] > 1000) test++;
}

int subsize = SIZE/4; // assume multiple of 4
for (int i = 0; i < 4; i++) {
data[i].array = values;
data[i].start_index = subsize*i;
data[i].end_index = subsize*(i+1);
}

for (int i = 0; i < 4; i++) {
}

return 0;
}``````

4) Ann-marie has the following errors when she tries to build. What type of error is it (compile, link, runtime, or logical)? How can she fix it?

``````thread-argv.c: In function ‘main’: