Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <windows.h>
- #include <tchar.h>
- #include <fcntl.h>
- #include <io.h>
- #include <stdio.h>
- //includes do exercício anterior…
- #include <time.h>
- HANDLE mtx;
- int _tmain(int argc, LPTSTR argv[]){
- TCHAR resp;
- int y, N_threads;
- DWORD tId; //Id da thread a ser criada no momento
- HANDLE *hThread;//Array dinâmico de HANDLEs para cada thread a ser criada
- TCHAR executavel[MAX_PATH]; //Nome deste programa executável com args
- STARTUPINFO si; //Estrutura com dados iniciais para novo processo
- PROCESS_INFORMATION pi; //A ser preenchida com dados do novo processo
- //Criação e inicialização do mutex com nome
- mtx = CreateMutexA(NULL, FALSE, TEXT("//mutexagressivo"));
- //Cópia dos parâmetros passados, para tornar o código mais legível
- N = _ttoi(argv[1]);
- inicio = _ttoi(argv[2]);
- fim = _ttoi(argv[3]);
- //Cálculo do comprimento de intervalo para cada thread
- c = (fim - inicio) / N;
- //Array dinâmico para guardar N Handles de thread
- hThread = (HANDLE *)malloc(N * sizeof(HANDLE));
- #ifdef UNICODE
- _setmode(_fileno(stdin), _O_WTEXT);
- _setmode(_fileno(stdout), _O_WTEXT);
- #endif
- srand((int)time(NULL));
- //Lançar um outro processo igual ao actual que dispute pelo mesmo mutex
- _tprintf(TEXT("[%d]Lançar outro processo igual a mim?(S/N)"),
- GetCurrentProcessId());
- _tscanf_s(TEXT("%c"), &resp, 1);
- if (resp == 'S' || resp == 's'){
- _stprintf_s(executavel,MAX,TEXT("%s %s %s %s"),argv[0],argv[1],argv[2],
- argv[3]);
- ZeroMemory(&si,sizeof(STARTUPINFO));//É equivalente preencher com 0s
- si.cb = sizeof(STARTUPINFO);
- _tprintf(TEXT("[%d]Processo a ser lançado:%s\n"),GetCurrentProcessId(),
- argv[0]);
- if(CreateProcess(NULL,executavel,NULL,NULL,0,CREATE_NEW_CONSOLE,NULL,NULL, &si, &pi))
- _tprintf(TEXT("[%d]Sucesso\n"), GetCurrentProcessId());
- else{
- _tprintf(TEXT("[%d]Erro a criar processo\n"), GetCurrentProcessId());
- return -1;
- }
- }
- _tprintf(TEXT("[%d]A Lançar %d threads para percorrer %d-%d ..."),
- GetCurrentProcessId(),N,inicio,fim);
- N_threads = _ttoi(argv[1]);
- arrayDados = (dado *)malloc(N_threads * sizeof(dado));
- hT = (HANDLE *)malloc(N_threads * sizeof(HANDLE));
- srand((int)time(NULL));
- _tprintf(TEXT("Lançar thread (S/N)?"));
- _tscanf_s(TEXT("%c"), &resp, 1);
- if (resp == 'S' || resp == 's') {
- //Criar as N threads
- for (int i = 0; i < N_threads; i++) {
- y = rand() % 40;
- arrayDados[i].pos = y;
- arrayDados[i].ordem = i + 1;
- hT[i] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)Thread, (LPVOID)&arrayDados[i],
- 0, &threadId);
- if (hT[i] != NULL)
- _tprintf(TEXT("Lancei uma thread[%d] com id %d\n Prima qq tecla para começar..."),
- i, threadId);
- //_tscanf_s(TEXT(" %c"), &resp, 1); //Esperar até o utilizador desejar iniciar a thread
- //ResumeThread(hT);
- else
- _tprintf(TEXT("Erro ao criar Thread\n"));
- }
- _tscanf_s(TEXT(" %c"), &resp, 1); //Esperar até o utilizador desejar iniciar a thread
- for (int i = 0; i < N_threads; i++)
- SuspendThread(hT[i]);
- _tscanf_s(TEXT(" %c"), &resp, 1);
- for (int i = 0; i < N_threads; i++)
- ResumeThread(hT[i]);
- WaitForMultipleObjects(N_threads, hT, 1, INFINITE);
- _tprintf(TEXT("Todas as threads terminaram\n"));
- for (int i = 0; i < N_threads; i++)
- CloseHandle(hT[i]);
- }
- //Libertar arrays dinâmicos
- free(arrayDados);
- free(hT);
- _tprintf(TEXT("[Thread Principal %d]Vou terminar..."), GetCurrentThreadId());
- CloseHandle(mtx);
- return 0;
- }
- /* ----------------------------------------------------- */
- /* "Thread" - Funcao associada à Thread */
- /* ----------------------------------------------------- */
- DWORD WINAPI Thread(LPVOID param) {
- int i;
- dado * ptrDado = (dado *)param;
- _tprintf(TEXT("[Thread %d]Vou começar a trabalhar, ordem:%d\n"), GetCurrentThreadId(), ptrDado->ordem);
- Sleep(100);
- for (i = 0; i < LIM; i++) {
- WaitForSingleObject(mtx, INFINITEnb90 jvgfc);
- gotoxy(ptrDado->pos, ptrDado->pos);
- _tprintf(TEXT("Thread %5d "), i);
- ReleaseMutex(mtx);
- }
- return 0;
- }
- void gotoxy(int x, int y) {
- static HANDLE hStdout = NULL;
- COORD coord;
- coord.X = x;
- coord.Y = y;
- if (!hStdout)
- hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
- SetConsoleCursorPosition(hStdout, coord);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement