Modify PID Manager with threads

This commit is contained in:
Fabio Scotto di Santolo
2024-08-28 18:18:10 +02:00
parent c5002973e6
commit b941fca02a
4 changed files with 103 additions and 1 deletions

31
threads/ex417.c Normal file
View File

@@ -0,0 +1,31 @@
#include <pthread.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int value = 0;
void *runner(void *param);
int main(int argc, char *argv[]) {
pid_t pid;
pthread_t tid;
pthread_attr_t attr;
pid = fork();
if (pid == 0) {
pthread_attr_init(&attr);
pthread_create(&tid, &attr, runner, NULL);
pthread_join(tid, NULL);
printf("CHILD: value = %d\n", value);
} else if (pid > 0) {
wait(NULL);
printf("PARENT: value = %d\n", value);
}
}
void *runner(void *param) {
value = 5;
pthread_exit(0);
}

View File

@@ -34,7 +34,7 @@ void release_pid(int pid) {
int main(void) {
if (allocate_map() != 1) {
perror("Failed to initialiaze PID Manager\n");
perror("Failed to initialize PID Manager\n");
exit(1);
}

View File

@@ -1,5 +1,6 @@
#if !defined(__PID_MANGER_H__)
#define __PID_MANGER_H__
#define _GNU_SOURCE
// Crea e inizializza una struttura per rappresentare i pid;
// restituisce -1 in caso di insuccesso e 1 in caso di successo.

View File

@@ -0,0 +1,70 @@
#include "pid_manager.h"
#include <pthread.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#define MIN_PID 300
#define MAX_PID 5000
#define SIZE (MAX_PID - MIN_PID + 1)
bool pids[SIZE];
void *runner(void *param);
int allocate_map(void) {
for (int i = 0; i < SIZE; i++) {
pids[i] = false;
}
return 1;
}
int allocate_pid(void) {
for (int i = 0; i < SIZE; i++) {
if (!pids[i]) {
pids[i] = true;
return i + MIN_PID;
}
}
return -1;
}
void release_pid(int pid) {
if (pid >= MIN_PID && pid <= MAX_PID) {
pids[pid - MIN_PID] = false;
}
}
void *runner(void *param) {
const pid_t self = gettid();
const int pid = allocate_pid();
printf("Run thread %d handle PID %d.\n", self, pid);
sleep(rand() % 31);
release_pid(pid);
printf("Thread %d ended\n", self);
pthread_exit(0);
}
int main(void) {
const int thread_count = 100;
pthread_t threads[thread_count];
if (!allocate_map()) {
perror("Failed to allocate PID Manager\n");
exit(EXIT_FAILURE);
}
for (int i = 0; i < thread_count; i++) {
printf("Created thread %d\n", i);
pthread_create(&threads[i], NULL, runner, NULL);
}
for (int i = 0; i < thread_count; i++) {
printf("Waiting thread %d\n", i);
pthread_join(threads[i], NULL);
}
return EXIT_SUCCESS;
}