Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <windows.h>
- #include <process.h>
- #include <cmath>
- #include <iostream>
- const unsigned count = 1000;
- CRITICAL_SECTION cs;
- double y[count];
- double sum = 0;
- int x = 0;
- void WINAPIV thread(void* num)
- {
- while (x < count)
- {
- //Входим в critical section
- EnterCriticalSection(&cs);
- if (x < count)
- {
- //Считаем значение функции, сумму
- y[x] = sin(static_cast<double>(x + 1) / 10000);
- sum += y[x];
- x++;
- //Выводим на экран сведения о счете
- std::cout << "Thread: " << (int)num << " ";
- std::cout << "sin(x)=" << y[x - 1] << " ";
- std::cout << "sum=" << sum << " ";
- std::cout << "x=" << static_cast<double>(x) / 10000 << std::endl;
- }
- //Выходим из critical section
- LeaveCriticalSection(&cs);
- }
- //Безопасно завершаем поток
- _endthread();
- }
- int main(int argc, char* argv[])
- {
- SetConsoleOutputCP(1251);
- //Создаем массив для хранения handle потоков
- const unsigned threadsCount = 3;
- HANDLE hThread[threadsCount];
- //Инициализируем critical section
- InitializeCriticalSection(&cs);
- //Создаем потоки
- for (int i = 0; i < threadsCount; i++)
- hThread[i] = (HANDLE)_beginthread(&thread, 0, (void*)(i + 1));
- //Ждем завершения всех потоков
- WaitForMultipleObjects(threadsCount, hThread, TRUE, INFINITE);
- //Удаляем critical section
- DeleteCriticalSection(&cs);
- std::cout << "Сумма: " << sum << std::endl;
- system("pause");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement