Last active
September 3, 2021 18:20
-
-
Save luissimas/8fa30f18e7ceed36ba13652eb757feee to your computer and use it in GitHub Desktop.
so_atividade_threads
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Autor(es): Luís Augusto Simas do Nascimento | |
Data de Criação: 03/09/2021 | |
Data de Atualização: 03/09/2021 | |
Objetivos: Testar a criação de processos e threads | |
*/ | |
// Bibliotecas | |
#include <pthread.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <sys/wait.h> | |
#include <unistd.h> | |
#define NTEST 1000 | |
void test_processes(int); | |
void test_threads(int); | |
void compare_time(); | |
void *thread_routine(void *); | |
// Função principal | |
int main(int argc, char *argv[]) { | |
// test_processes(0); | |
// test_threads(0); | |
compare_time(); | |
return 0; | |
} | |
void test_processes(int max) { | |
pid_t pid; | |
int count = 0; | |
int wstatus; | |
while ((max == 0) || (count <= max)) { | |
// Create a new process | |
pid = fork(); | |
if (pid < 0) { | |
perror("Erro ao criar o novo processo"); | |
break; | |
} else if (pid == 0) { | |
// Just put the child processes to sleep | |
sleep(2); | |
exit(0); | |
} | |
count++; | |
} | |
// Waiting for the children to die | |
wait(&wstatus); | |
printf("Ao todo foram criados %d processos!\n", count); | |
} | |
void test_threads(int max) { | |
pthread_t thread; | |
int count = 0; | |
while ((max == 0) || (count <= max)) { | |
if (pthread_create(&thread, NULL, thread_routine, NULL) != 0) { | |
perror("Erro ao criar thread"); | |
break; | |
} | |
count++; | |
}; | |
printf("Ao todo foram criadas %d threads!\n", count); | |
} | |
void compare_time() { | |
struct timespec start, end; | |
float ptime, ttime; | |
if (clock_gettime(CLOCK_REALTIME, &start) < 0) { | |
printf("Erro em clock_gettime"); | |
} | |
test_processes(NTEST); | |
if (clock_gettime(CLOCK_REALTIME, &end) < 0) { | |
printf("Erro em clock_gettime"); | |
} | |
ptime = | |
(end.tv_sec + end.tv_nsec / 10e9) - (start.tv_sec + start.tv_nsec / 10e9); | |
if (clock_gettime(CLOCK_REALTIME, &start) < 0) { | |
printf("Erro em clock_gettime"); | |
} | |
test_threads(NTEST); | |
if (clock_gettime(CLOCK_REALTIME, &end) < 0) { | |
printf("Erro em clock_gettime"); | |
} | |
ttime = | |
(end.tv_sec + end.tv_nsec / 10e9) - (start.tv_sec + start.tv_nsec / 10e9); | |
printf("Tempo total para criar %d processos: %f\n", NTEST, ptime); | |
printf("Tempo total para criar %d threads: %f\n", NTEST, ttime); | |
} | |
void *thread_routine(void *_) { | |
sleep(5); | |
pthread_exit(0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment