#include <Windows.h>
inline void demo_proc(int index)
{
for (int i = 1; i <= 10000000; i++)
{
demo_acc[index] += (float)(((i % 2) * -1) * 2 + 1);
}
}
DWORD WINAPI DispProc0(LPVOID lpVoid)
{
int *flag = (int *)lpVoid;
while (*flag < 0)
{
_mm_pause();
}
int index = *flag;
DWORD tickCount = GetTickCount();
for (int i = 0; i < 13; i++)
{
demo_proc(index + i);
}
printf("thread %d cost %d ms looping from %d to %d.\r\n", index / 13, GetTickCount() - tickCount, index, index + 13);
return 0;
}
DWORD WINAPI DispProc1(LPVOID lpVoid)
{
int *flag = (int *)lpVoid;
while (*flag < 0)
{
_mm_pause();
}
int index = *flag;
DWORD tickCount = GetTickCount();
for (int i = 0; i < 16; i++)
{
demo_proc(index + i);
}
printf("thread %d cost %d ms looping from %d to %d.\r\n", index / 16, GetTickCount() - tickCount, index, index + 16);
return 0;
}
DWORD WINAPI DispProc2(LPVOID lpVoid)
{
int *flag = (int *)lpVoid;
while (*flag < 0)
{
_mm_pause();
}
int index = *flag;
DWORD tickCount = GetTickCount();
for (int i = index; i < (13 * 4); i++)
{
demo_proc(i);
}
printf("thread %d cost %d ms looping from %d to %d.\r\n", index / 16, GetTickCount() - tickCount, index, 13 * 4);
return 0;
}
int main(int argc, char **argv)
{
volatile int index[4] = { -1 }; // ###
HANDLE threads[4];
DWORD tickCount = GetTickCount();
for (int i = 0; i < (13 * 4); i++)
{
demo_proc(i);
}
printf("single thread cost %d ms.\r\n", GetTickCount() - tickCount);
for (int i = 0; i < 4; i++)
{
index[i] = -1;
threads[i] = CreateThread(NULL, 0, DispProc0, (LPVOID)(index + i), 0, NULL);
}
tickCount = GetTickCount();
for (int i = 0; i < 4; i++)
{
index[i] = i * 13;
}
WaitForMultipleObjects(4, threads, TRUE, INFINITE);
printf("simple multi-thread cost %d ms.\r\n", GetTickCount() - tickCount);
for (int i = 0; i < 4; i++)
{
CloseHandle(threads[i]);
}
for (int i = 0; i < 4; i++)
{
index[i] = -1;
threads[i] = CreateThread(NULL, 0, i == 3 ? DispProc2 : DispProc1, (LPVOID)(index + i), 0, NULL);
}
tickCount = GetTickCount();
for (int i = 0; i < 4; i++)
{
index[i] = i * 16;
}
WaitForMultipleObjects(4, threads, TRUE, INFINITE);
printf("aligned multi-thread cost %d ms.\r\n", GetTickCount() - tickCount);
for (int i = 0; i < 4; i++)
{
CloseHandle(threads[i]);
}
return 0;
}
运行效果:
下一篇将演示使用缓存进行高性能的线程同步。