Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // aula_thread.cpp : Defines the entry point for the console application.
- //
- #include<Windows.h>
- #include<process.h>
- #include<stdio.h>
- #include<stdlib.h>
- #include<time.h>
- #include<iostream>
- #include<vector>
- #define dim 10000
- #define threads 4
- typedef struct{
- int li, lf, ci, cf, soma;
- }par;
- int mat[dim][dim];
- void preencher_matriz();
- void qtd_primos(void *parThread);
- bool eh_primo(int x);
- int main()
- {
- srand (time(NULL));
- DWORD ThreadIdentifier[threads];
- HANDLE idThread[threads];
- par parametro[threads];
- //clock_t inicio, fim;
- int total_primos = 0;
- preencher_matriz();
- for(int i = 0; i < threads; i++)
- {
- parametro[i].li = 0;
- parametro[i].lf = dim;
- parametro[i].ci = 0 + (dim/threads)*i;
- parametro[i].cf = (dim/threads) + (dim/threads)*i;
- parametro[i].soma = 0;
- }
- for(int i = 0; i < threads; i++)
- {
- idThread[i] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)qtd_primos, ¶metro[i], 0, &ThreadIdentifier[i]);
- }
- WaitForMultipleObjects(threads, idThread, TRUE, INFINITE);
- //WaitForSingleObject(idThread[1], INFINITE);
- for(int i = 0; i < threads; i++)
- {
- CloseHandle(idThread[i]);
- }
- for(int i = 0; i < threads; i++)
- {
- total_primos += parametro[i].soma;
- }
- printf("Qtd de primos: %d\n", total_primos);
- getchar();
- return 0;
- }
- void preencher_matriz()
- {
- for(int i = 0; i < dim; i++)
- {
- for(int j = 0; j < dim; j++)
- {
- mat[i][j] = rand()%1000000;
- }
- }
- }
- void qtd_primos(void *parThread)
- {
- par *parFuncao = (par *) parThread;
- printf("linha_inicial: %d\tlinha final: %d\n", parFuncao->li, parFuncao->lf);
- printf("coluna_inicial: %d\tcoluna final: %d\n", parFuncao->ci, parFuncao->cf);
- for(int i = parFuncao->li; i < parFuncao->lf; i++)
- {
- for(int j = parFuncao->ci; j < parFuncao->cf; j++)
- {
- parFuncao->soma += eh_primo(mat[i][j]);
- }
- }
- }
- bool eh_primo(int x)
- {
- if(x % 2 == 0 && x!=2)
- {
- return(0);
- }
- else if(x == 2)
- {
- return(1);
- }
- else
- {
- int aux = 0;
- for(int i = 1; i <= x; i+=2)
- {
- if(x % i == 0)
- {
- aux++;
- }
- if(aux >= 3)
- {
- return(0);
- }
- }
- if(aux == 2)
- {
- return(1);
- }
- else
- {
- return(0);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement