我正在做memcpy函数的优化任务,我在这里找到了这个链接。 How to increase performance of memcpymemcpy的多线程编程
由于我不熟悉多线程编程,我不知道如何将代码插入到原始主函数中?如何将原始问题中的代码修改为多线程memcpy项目?我的意思是,如何为这个多线程memcpy项目创建一个完整的项目。在原始主函数中插入函数startCopyThreads或stopCopyThreads或mt_memcpy函数的地方在哪里?
#define NUM_CPY_THREADS 4
HANDLE hCopyThreads[NUM_CPY_THREADS] = {0};
HANDLE hCopyStartSemaphores[NUM_CPY_THREADS] = {0};
HANDLE hCopyStopSemaphores[NUM_CPY_THREADS] = {0};
typedef struct
{
int ct;
void * src, * dest;
size_t size;
} mt_cpy_t;
mt_cpy_t mtParamters[NUM_CPY_THREADS] = {0};
DWORD WINAPI thread_copy_proc(LPVOID param)
{
mt_cpy_t * p = (mt_cpy_t *) param;
while(1)
{
WaitForSingleObject(hCopyStartSemaphores[p->ct], INFINITE);
memcpy(p->dest, p->src, p->size);
ReleaseSemaphore(hCopyStopSemaphores[p->ct], 1, NULL);
}
return 0;
}
int startCopyThreads()
{
for(int ctr = 0; ctr < NUM_CPY_THREADS; ctr++)
{
hCopyStartSemaphores[ctr] = CreateSemaphore(NULL, 0, 1, NULL);
hCopyStopSemaphores[ctr] = CreateSemaphore(NULL, 0, 1, NULL);
mtParamters[ctr].ct = ctr;
hCopyThreads[ctr] = CreateThread(0, 0, thread_copy_proc, &mtParamters[ctr], 0, NULL);
}
return 0;
}
void * mt_memcpy(void * dest, void * src, size_t bytes)
{
//set up parameters
for(int ctr = 0; ctr < NUM_CPY_THREADS; ctr++)
{
mtParamters[ctr].dest = (char *) dest + ctr * bytes/NUM_CPY_THREADS;
mtParamters[ctr].src = (char *) src + ctr * bytes/NUM_CPY_THREADS;
mtParamters[ctr].size = (ctr + 1) * bytes/NUM_CPY_THREADS - ctr * bytes/ NUM_CPY_THREADS;
}
//release semaphores to start computation
for(int ctr = 0; ctr < NUM_CPY_THREADS; ctr++)
ReleaseSemaphore(hCopyStartSemaphores[ctr], 1, NULL);
//wait for all threads to finish
WaitForMultipleObjects(NUM_CPY_THREADS, hCopyStopSemaphores, TRUE, INFINITE);
return dest;
}
int stopCopyThreads()
{
for(int ctr = 0; ctr < NUM_CPY_THREADS; ctr++)
{
TerminateThread(hCopyThreads[ctr], 0);
CloseHandle(hCopyStartSemaphores[ctr]);
CloseHandle(hCopyStopSemaphores[ctr]);
}
return 0;
}
你要去哪里?你是否希望通过使用多线程来提高'memcpy()'的性能? – NPE 2013-03-21 07:05:38
@NPE是的,这就是我想要的。 – zjluoxiao 2013-03-21 07:07:36
基本上你会从你的主函数调用mt_memcpy。对于它的价值,这不太可能实际上提高memcpy的速度。信号量和线程的开销远远超过了大部分memcpy的开销。但是在你的代码中使用它之前,你应该测量它。 – 2013-03-21 07:15:05