Last active
June 23, 2020 04:16
-
-
Save mfilipelino/2c4e336f78ba5fe13cf9 to your computer and use it in GitHub Desktop.
#pthread
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
#include <pthread.h> | |
#include <stdio.h> | |
#define NUM_ARGS 2 | |
typedef struct{ | |
int id; | |
}Data; | |
void printData(Data *d){ | |
printf("id: %d\n", d->id); | |
} | |
void createData(Data *d, int id){ | |
d->id = id; | |
} | |
void* thread_process(void* dt){ | |
Data* data = (Data*) dt; | |
printData(data); | |
pthread_exit(NULL); | |
} | |
int main(int argc, char* argv[]){ | |
int i; | |
int numero_threads = 0; | |
if(argc != NUM_ARGS){ | |
fprintf(stderr, "[Erro] O número de argumentos deve ser igual a 2\n"); | |
return 0; | |
} | |
else{ | |
numero_threads = atoi(argv[1]); | |
start_threads(numero_threads); | |
} | |
return 1; | |
} | |
int start_threads(int num_threads){ | |
pthread_t threads[num_threads]; | |
Data datas[num_threads]; | |
int i; | |
for(i = 0; i < num_threads; i++){ | |
createData(&datas[i], i); | |
pthread_create(&threads[i], NULL, &thread_process, (void *) &datas[i]); | |
} | |
for(i = 0; i < num_threads; i++){ | |
pthread_join(threads[i], NULL); | |
} | |
pthread_exit(NULL); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment