マルチスレッドプログラミング(CreateThread利用)

マルチスレッドプログラミングにおける構造体を使ったデータのやりとりサンプルメモ

注:これが一般的化どうかはわかりません


#include
using namespace std;

#include
#include

typedef struct tagTEST
{
int i;
int* a;
int* b;
int* c;
int size;
} TEST;

DWORD WINAPI thread(LPVOID pParam)
{
TEST* test = (TEST*)pParam;
cout << "thread start : " << test->i << endl;
for(int i = 0; i < test->size; i++)
{
test->c[i] = test->a[i] + test->b[i];
}
cout << "thread end : " << test->i << endl;

return 0;
}

int main(void)
{
const int size = 16;
const int core = 8;
int a[size];
int b[size];
int c[size];
for(int i = 0; i < size; i++)
{
a[i] = i;
b[i] = i*2;
c[i] = 0;
}

TEST* test;
test = new TEST[size];

for(int i = 0; i < core; i++)
{
test[i].i = i;
test[i].a = &a[i*size/core];
test[i].b = &b[i*size/core];
test[i].c = &c[i*size/core];
test[i].size = size/core;
}

HANDLE* hThread;
hThread = new HANDLE[core];

for(int i = 0; i < core; i++)
{
hThread[i] = CreateThread(NULL, sizeof(test[i]), thread, &test[i], 0, 0);
}
WaitForMultipleObjects(core, hThread, TRUE, INFINITE);

for(int i = 0; i < core; i++)
{
CloseHandle(hThread[i]);
}

for(int i = 0; i < size; i++)
{
cout << a[i] << "+" << b[i] << "=" << c[i] << endl;
}

return 0;
}

以上のコードを実行すると、出力は以下の通り


thread start : 0
thread end : 0
thread start : 6
thread end : 6
thread start : 4
thread end : 4
thread start : 1
thread end : 1
thread start : 2
thread end : 2
thread start : 3
thread end : 3
thread start : 7
thread end : 7
thread start : 5
thread end : 5
0+0=0
1+2=3
2+4=6
3+6=9
4+8=12
5+10=15
6+12=18
7+14=21
8+16=24
9+18=27
10+20=30
11+22=33
12+24=36
13+26=39
14+28=42
15+30=45