Mandatory task 3 ING2504 Fall 2025¶
Part 1: Basic locking¶
Compile and execute the following C-program. Note this will run forever or until you stop it by pressing CTRL-C (this sends a SIGINT-signal to the process which will make the operating system terminate the process).
#include <stdio.h>
#include <pthread.h>
#include <string.h>
typedef struct {
char name[100];
int age;
} Person;
Person person;
void *thread1_func(void *arg) {
int counter=0;
int noerror=1;
while(1) {
counter++;
strcpy(person.name, "Alice");
person.age = 30;
if (strcmp(person.name, "Alice") != 0 || person.age != 30) {
printf("Thread 1: Alice is not 30! she is %d\n", person.age);
noerror=0;
}
if (noerror == 1 && (counter % 1000000 == 0)) {
printf("Hey you rock! Alice's OK!\n");
}
}
return NULL;
}
void *thread2_func(void *arg) {
int counter=0;
int noerror=1;
while(1) {
counter++;
strcpy(person.name, "Bob");
person.age = 25;
if (strcmp(person.name, "Bob") != 0 || person.age != 25) {
printf("Thread 2: Bob is not 25! he is %d\n", person.age);
noerror=0;
}
if (noerror == 1 && (counter % 1000000 == 0)) {
printf("Hey you rock! Bob's OK!\n");
}
}
return NULL;
}
int main() {
pthread_t thread1, thread2;
pthread_create(&thread1, NULL, thread1_func, NULL);
pthread_create(&thread2, NULL, thread2_func, NULL);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
return 0;
}
This will generate output like this:
Thread 2: Bob is not 25! he is 30
Thread 2: Bob is not 25! he is 30
Thread 1: Alice is not 30! she is 25
Thread 1: Alice is not 30! she is 25
Thread 1: Alice is not 30! she is 25
Thread 2: Bob is not 25! he is 30
Thread 1: Alice is not 30! she is 25
Add locks to the two threads in such a way that the output instead will be:
Hey you rock! Alice's OK!
Hey you rock! Bob's OK!
Hey you rock! Bob's OK!
Hey you rock! Alice's OK!
Hey you rock! Bob's OK!
- Make sure to keep the parallelism: do not insert locks in a way that will cause only one thread to execute.
- Place the locks only around the statements where you really need locks.
Part 2: Reader-Writer¶
In the compendia chapter 8, do the exercise number 5 (5. (KEY PROBLEM) In chapter 31, Homework (code), let us do the following...). Note: you only have to demonstrate part (d) to your teaching assistant.