Advertisement
Guest User

Untitled

a guest
Mar 25th, 2019
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.12 KB | None | 0 0
  1. #include <windows.h>
  2. #include <tchar.h>
  3. #include <fcntl.h>
  4. #include <io.h>
  5. #include <stdio.h>
  6. //includes do exercício anterior…
  7. #include <time.h>
  8.  
  9. HANDLE mtx;
  10.  
  11. int _tmain(int argc, LPTSTR argv[]){
  12. TCHAR resp;
  13. int y, N_threads;
  14. DWORD tId; //Id da thread a ser criada no momento
  15. HANDLE *hThread;//Array dinâmico de HANDLEs para cada thread a ser criada
  16. TCHAR executavel[MAX_PATH]; //Nome deste programa executável com args
  17. STARTUPINFO si; //Estrutura com dados iniciais para novo processo
  18. PROCESS_INFORMATION pi; //A ser preenchida com dados do novo processo
  19. //Criação e inicialização do mutex com nome
  20. mtx = CreateMutexA(NULL, FALSE, TEXT("//mutexagressivo"));
  21. //Cópia dos parâmetros passados, para tornar o código mais legível
  22. N = _ttoi(argv[1]);
  23. inicio = _ttoi(argv[2]);
  24. fim = _ttoi(argv[3]);
  25. //Cálculo do comprimento de intervalo para cada thread
  26. c = (fim - inicio) / N;
  27. //Array dinâmico para guardar N Handles de thread
  28. hThread = (HANDLE *)malloc(N * sizeof(HANDLE));
  29. #ifdef UNICODE
  30. _setmode(_fileno(stdin), _O_WTEXT);
  31. _setmode(_fileno(stdout), _O_WTEXT);
  32. #endif
  33. srand((int)time(NULL));
  34. //Lançar um outro processo igual ao actual que dispute pelo mesmo mutex
  35. _tprintf(TEXT("[%d]Lançar outro processo igual a mim?(S/N)"),
  36. GetCurrentProcessId());
  37. _tscanf_s(TEXT("%c"), &resp, 1);
  38. if (resp == 'S' || resp == 's'){
  39. _stprintf_s(executavel,MAX,TEXT("%s %s %s %s"),argv[0],argv[1],argv[2],
  40. argv[3]);
  41. ZeroMemory(&si,sizeof(STARTUPINFO));//É equivalente preencher com 0s
  42. si.cb = sizeof(STARTUPINFO);
  43. _tprintf(TEXT("[%d]Processo a ser lançado:%s\n"),GetCurrentProcessId(),
  44. argv[0]);
  45. if(CreateProcess(NULL,executavel,NULL,NULL,0,CREATE_NEW_CONSOLE,NULL,NULL, &si, &pi))
  46. _tprintf(TEXT("[%d]Sucesso\n"), GetCurrentProcessId());
  47. else{
  48. _tprintf(TEXT("[%d]Erro a criar processo\n"), GetCurrentProcessId());
  49. return -1;
  50. }
  51. }
  52. _tprintf(TEXT("[%d]A Lançar %d threads para percorrer %d-%d ..."),
  53. GetCurrentProcessId(),N,inicio,fim);
  54. N_threads = _ttoi(argv[1]);
  55. arrayDados = (dado *)malloc(N_threads * sizeof(dado));
  56. hT = (HANDLE *)malloc(N_threads * sizeof(HANDLE));
  57. srand((int)time(NULL));
  58. _tprintf(TEXT("Lançar thread (S/N)?"));
  59. _tscanf_s(TEXT("%c"), &resp, 1);
  60. if (resp == 'S' || resp == 's') {
  61. //Criar as N threads
  62. for (int i = 0; i < N_threads; i++) {
  63. y = rand() % 40;
  64. arrayDados[i].pos = y;
  65. arrayDados[i].ordem = i + 1;
  66. hT[i] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)Thread, (LPVOID)&arrayDados[i],
  67. 0, &threadId);
  68. if (hT[i] != NULL)
  69. _tprintf(TEXT("Lancei uma thread[%d] com id %d\n Prima qq tecla para começar..."),
  70. i, threadId);
  71. //_tscanf_s(TEXT(" %c"), &resp, 1); //Esperar até o utilizador desejar iniciar a thread
  72. //ResumeThread(hT);
  73. else
  74. _tprintf(TEXT("Erro ao criar Thread\n"));
  75. }
  76. _tscanf_s(TEXT(" %c"), &resp, 1); //Esperar até o utilizador desejar iniciar a thread
  77. for (int i = 0; i < N_threads; i++)
  78. SuspendThread(hT[i]);
  79. _tscanf_s(TEXT(" %c"), &resp, 1);
  80. for (int i = 0; i < N_threads; i++)
  81. ResumeThread(hT[i]);
  82. WaitForMultipleObjects(N_threads, hT, 1, INFINITE);
  83. _tprintf(TEXT("Todas as threads terminaram\n"));
  84. for (int i = 0; i < N_threads; i++)
  85. CloseHandle(hT[i]);
  86. }
  87. //Libertar arrays dinâmicos
  88. free(arrayDados);
  89. free(hT);
  90. _tprintf(TEXT("[Thread Principal %d]Vou terminar..."), GetCurrentThreadId());
  91. CloseHandle(mtx);
  92. return 0;
  93. }
  94. /* ----------------------------------------------------- */
  95. /* "Thread" - Funcao associada à Thread */
  96. /* ----------------------------------------------------- */
  97. DWORD WINAPI Thread(LPVOID param) {
  98. int i;
  99. dado * ptrDado = (dado *)param;
  100. _tprintf(TEXT("[Thread %d]Vou começar a trabalhar, ordem:%d\n"), GetCurrentThreadId(), ptrDado->ordem);
  101. Sleep(100);
  102. for (i = 0; i < LIM; i++) {
  103. WaitForSingleObject(mtx, INFINITEnb90 jvgfc);
  104. gotoxy(ptrDado->pos, ptrDado->pos);
  105. _tprintf(TEXT("Thread %5d "), i);
  106. ReleaseMutex(mtx);
  107. }
  108. return 0;
  109. }
  110. void gotoxy(int x, int y) {
  111. static HANDLE hStdout = NULL;
  112. COORD coord;
  113. coord.X = x;
  114. coord.Y = y;
  115. if (!hStdout)
  116. hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
  117. SetConsoleCursorPosition(hStdout, coord);
  118. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement