Advertisement
AlukardBF

os_laba2

Mar 11th, 2017
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <windows.h>
  2. #include <process.h>
  3. #include <cmath>
  4. #include <iostream>
  5.  
  6. const unsigned count = 1000;
  7. CRITICAL_SECTION cs;
  8. double y[count];
  9. double sum = 0;
  10. int x = 0;
  11.  
  12. void WINAPIV thread(void* num)
  13. {
  14.     while (x < count)
  15.     {
  16.         //Входим в critical section
  17.         EnterCriticalSection(&cs);
  18.         if (x < count)
  19.         {
  20.             //Считаем значение функции, сумму
  21.             y[x] = sin(static_cast<double>(x + 1) / 10000);
  22.             sum += y[x];
  23.             x++;
  24.             //Выводим на экран сведения о счете
  25.             std::cout << "Thread: " << (int)num << " ";
  26.             std::cout << "sin(x)=" << y[x - 1] << " ";
  27.             std::cout << "sum=" << sum << " ";
  28.             std::cout << "x=" << static_cast<double>(x) / 10000 << std::endl;
  29.         }
  30.         //Выходим из critical section
  31.         LeaveCriticalSection(&cs);
  32.     }
  33.     //Безопасно завершаем поток
  34.     _endthread();
  35. }
  36.  
  37. int main(int argc, char* argv[])
  38. {
  39.     SetConsoleOutputCP(1251);
  40.     //Создаем массив для хранения handle потоков
  41.     const unsigned threadsCount = 3;
  42.     HANDLE hThread[threadsCount];
  43.     //Инициализируем critical section
  44.     InitializeCriticalSection(&cs);
  45.     //Создаем потоки
  46.     for (int i = 0; i < threadsCount; i++)
  47.         hThread[i] = (HANDLE)_beginthread(&thread, 0, (void*)(i + 1));
  48.     //Ждем завершения всех потоков
  49.     WaitForMultipleObjects(threadsCount, hThread, TRUE, INFINITE);
  50.     //Удаляем critical section
  51.     DeleteCriticalSection(&cs);
  52.     std::cout << "Сумма: " << sum << std::endl;
  53.     system("pause");
  54.     return 0;
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement