Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <windows.h>
- #include <tchar.h>
- #include <math.h>
- #include <stdio.h>
- #include <fcntl.h>
- #include <io.h>
- // funcionalidade relacionada com temporização
- static double PerfCounterFreq; // n ticks por seg.
- void initClock() {
- LARGE_INTEGER aux;
- if (!QueryPerformanceFrequency(&aux))
- _tprintf(TEXT("\nSorry - No can do em QueryPerfFreq\n"));
- PerfCounterFreq = (double)(aux.QuadPart); // / 1000.0;
- _tprintf(TEXT("\nTicks por sec.%f\n"), PerfCounterFreq);
- }
- __int64 startClock() {
- LARGE_INTEGER aux;
- QueryPerformanceCounter(&aux);
- return aux.QuadPart;
- }
- double stopClock(__int64 from) {
- LARGE_INTEGER aux;
- QueryPerformanceCounter(&aux);
- return (double)(aux.QuadPart - from) / PerfCounterFreq;
- }
- // estrutura de dados para controlar as threads
- typedef struct {
- int id;
- int limInf, limSup;
- int Result;
- int* contador;
- CRITICAL_SECTION *criticalSection;
- } TDados;
- // função da(s) thread(s)
- DWORD WINAPI ThreadMultiplos3(LPVOID param);
- // número * máximo * de threads
- // podem (e devem) ser menos
- #define MAX_THREADS 10
- int _tmain(int argc, TCHAR* argv[]) {
- HANDLE hThreads[MAX_THREADS]; // matriz de handles das threads
- DWORD threadId[MAX_THREADS];
- TDados tdados[MAX_THREADS]; // Matriz de dados para as threads;
- int numthreads; // número efectivo de threads
- unsigned int limsup; // limite superior
- __int64 clockticks; // variáveis para cronómetro
- double duracao;
- unsigned int range;
- unsigned int inter;
- int contador = 0;
- CRITICAL_SECTION criticalSection;
- int quantosNumerosParaCada = 0;
- #ifdef UNICODE
- _setmode(_fileno(stdin), _O_WTEXT);
- _setmode(_fileno(stdout), _O_WTEXT);
- #endif
- initClock();
- _tprintf(TEXT("\nLimite sup. -> "));
- _tscanf_s(TEXT("%u"), &limsup);
- _tprintf(TEXT("\nNum threads -> "));
- _tscanf_s(TEXT("%u"), &numthreads);
- if (numthreads > MAX_THREADS)
- numthreads = MAX_THREADS;
- InitializeCriticalSection(&criticalSection);
- EnterCriticalSection(&criticalSection);
- LeaveCriticalSection(&criticalSection);
- quantosNumerosParaCada = limsup / numthreads;
- for (int i = 0; i < numthreads; i++) {
- if (i == 0) {
- tdados[i].limSup = quantosNumerosParaCada;
- tdados[i].limInf = 1;
- }
- else {
- tdados[i].limInf = tdados[i - 1].limSup + 1;
- tdados[i].limSup = tdados[i].limInf + quantosNumerosParaCada - 1;
- }
- tdados[i].contador = &contador;
- tdados[i].criticalSection = &criticalSection;
- tdados[i].Result = 0;
- }
- // FAZER prepara e cria threads
- for (int i = 0; i < numthreads; i++) {
- hThreads[i] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ThreadMultiplos3, (LPVOID)&tdados[i], CREATE_SUSPENDED, &threadId[i]); //CREATE_SUSPENDED para nao comecar logo
- if (hThreads[i] != NULL) {
- _tprintf(TEXT("\nLancei uma thread Multiplos3 com id %d\n"), threadId[i]);
- tdados[i].id = threadId[i];
- }
- else
- _tprintf(TEXT("\nErro ao criar Thread\n"));
- }
- clockticks = startClock();
- // manda as threads começar
- for (int i = 0; i < numthreads; i++)
- ResumeThread(hThreads[i]); //comeca as threads so aqui
- // FAZER aguarda / controla as threads
- // manda as threads parar
- HANDLE ghEvents[MAX_THREADS];
- for (int i = 0; i < numthreads; i++)
- ghEvents[i] = hThreads[i];
- WaitForMultipleObjects(numthreads, ghEvents, TRUE, INFINITE);
- duracao = stopClock(clockticks);
- _tprintf(TEXT("\nSegundos=%f\n"), duracao);
- // FAZER apresenta resultados
- _tprintf(TEXT("Resultado do contador de Multiplos de 3: %d \n"), *tdados[0].contador);
- DeleteCriticalSection(&criticalSection);
- // Cód. ref. para aguardar por uma tecla – caso faça falta
- // _tprintf(TEXT("\nCarregue numa tecla"));
- // _gettch();
- return 0;
- }
- DWORD WINAPI ThreadMultiplos3(LPVOID param) { //começa sempre por DWORD WINAPI e recebe sempre um LPVOID
- int i, contador = 0;
- TDados* y = ((TDados*)param);
- _tprintf(TEXT("[Thread %d]Vou começar a trabalhar (%d - %d)\n"), GetCurrentThreadId(), y->limInf, y->limSup);
- Sleep(100);
- for (i = y->limInf; i <= y->limSup; i++) {
- if (i > 0 && i % 3 == 0) {
- y->Result = y->Result + i;
- contador++;
- _tprintf(TEXT(" %d é multiplo de 3. \n"), i);
- if (contador > 0 && contador % 200 == 0) {
- Sleep(1000);
- }
- EnterCriticalSection(y->criticalSection);
- (*(y->contador))++;
- LeaveCriticalSection(y->criticalSection);
- }
- }
- ExitThread(0);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement