update forking example

This commit is contained in:
Rokas Puzonas 2024-01-06 15:32:23 +02:00
parent 7321708c66
commit dd6a6b0e5e

View File

@ -8,45 +8,26 @@
#include <stdbool.h> #include <stdbool.h>
#include <time.h> #include <time.h>
// WARNING: This example does not work, I couldn't figure out why the child process goes into a deadlock on `pthread_mutex_lock` // WARNING: This example does not work, I couldn't figure out why the lock does not work correcly.
// The final counter result should not change, but it does.
struct shared_data { struct shared_data {
pthread_mutex_t mutex; pthread_mutex_t mutex;
int counter; int counter;
}; };
void milli_sleep(int milliseconds) {
struct timespec ts;
ts.tv_sec = milliseconds / 1000;
ts.tv_nsec = (milliseconds % 1000) * 1000000;
nanosleep(&ts, &ts);
}
float random_float() {
return (float)rand()/(float)RAND_MAX;
}
int random_range(int from, int to) {
return random_float()*(to-from) + from;
}
void run(const char *name, struct shared_data *data) { void run(const char *name, struct shared_data *data) {
printf("[%s] started, mutex: %p\n", name, &data->mutex); for (int i = 0; i < 10000; i++) {
for (int i = 0; i < 10; i++) {
if (pthread_mutex_lock(&data->mutex) != 0) { if (pthread_mutex_lock(&data->mutex) != 0) {
perror("pthread_mutex_lock"); perror("pthread_mutex_lock");
} }
int counter = data->counter; data->counter++;
milli_sleep(random_range(0, 100));
data->counter = counter + 1;
printf("[%s] counter is %d\n", name, counter + 1);
if (pthread_mutex_unlock(&data->mutex) != 0) { if (pthread_mutex_unlock(&data->mutex) != 0) {
perror("pthread_mutex_unlock"); perror("pthread_mutex_unlock");
} }
} }
printf("[%s] finished\n", name);
} }
int main() { int main() {
@ -75,5 +56,7 @@ int main() {
int child_status; int child_status;
waitpid(pid, &child_status, 0); waitpid(pid, &child_status, 0);
printf("Counter is %d\n", shared_data->counter);
} }