Добавил:
Kaz
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз:
Предмет:
Файл:
// example1.cpp: определяет точку входа для консольного приложения.
//
#include "stdafx.h"
#include "windows.h"
#include "time.h"
#include "stdlib.h"
#include <queue>
using namespace std;
#include <iostream>
using namespace std;
typedef DWORD (WINAPI *FUNCTYPE)(LPVOID lpParam);
typedef struct MyData {
int val1;
} MYDATA, *PMYDATA;
using namespace std;
class ThreadPool
{
public:
ThreadPool( int newNumber = 1)
{
if(newNumber > 0)
{
threadArray = (HANDLE *)calloc(newNumber, sizeof(HANDLE));
setNumber(newNumber);
func[0] = sum;
func[1] = mul;
func[2] = ret;
}
}
void setNumber( int num )
{
number = num;
PMYDATA myData;
for(int j = 0; j <= number - 1; j++)
{
myData = (PMYDATA) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
sizeof(MYDATA));
myData ->val1 = j;
threadArray[j] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)startProc,(LPVOID)myData, 0, NULL);
Sleep(100);
}
Sleep(100);
}
int getNumber()
{
return number;
}
void getUserInput()
{
int choice;
cout << "Input functions(0 - sum, 1 - mul, 2 - ret, 3 - exit)" << endl;
cin >> choice;
while((choice >= 0) && (choice <= 2))
{
threadQueue.push(func[choice]);
cin >> choice;
}
Dispetcher();
}
static DWORD WINAPI startProc(LPVOID lpParam)
{
//cout << "New process ID: " << GetCurrentThreadId() << endl;
return 1;
}
void Dispetcher()
{
FUNCTYPE oneFunction;
PMYDATA myData;
if(number <= 0)
{
cout << "There are no threads" << endl;
}
else
{
while(!threadQueue.empty())
{
myData = (PMYDATA) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
sizeof(MYDATA));
oneFunction = threadQueue.front();
threadQueue.pop();
DWORD dwRes = WaitForMultipleObjects(number, threadArray, FALSE, INFINITE);
myData ->val1 = dwRes;
TerminateThread(threadArray[dwRes], NULL);
threadArray[dwRes] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)oneFunction,(LPVOID)myData, 0, NULL);
cout << "Thread " << dwRes << " was run with new function\n";
}
for(int j = 0; j <= number - 1; j++)
{
WaitForSingleObject(threadArray[j], INFINITE);
TerminateThread(threadArray[j], NULL);
}
}
}
static DWORD WINAPI sum(LPVOID lpParam)
{
Sleep(10000);
cout << "Thread " << ((PMYDATA)lpParam) -> val1 << " function sum execute \n";
return 1;
}
static DWORD WINAPI mul(LPVOID lpParam)
{
Sleep(20000);
cout <<"Thread " << ((PMYDATA)lpParam) -> val1 << " function mul execute\n";
return 1;
}
static DWORD WINAPI ret(LPVOID lpParam)
{
Sleep(3000);
cout << "Thread " << ((PMYDATA)lpParam) -> val1 <<" function ret execute\n" ;
return 1;
}
DWORD (WINAPI *func[3])(LPVOID lpParam);
private:
int number;
queue<FUNCTYPE> threadQueue;
HANDLE * threadArray;
};
void main()
{
int n;
cout << "Input number of threads" << endl;
cin >> n;
ThreadPool myThread( n );
myThread.getUserInput();
cin >> n;
return ;
}
Соседние файлы в папке example1