首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >memcpy的多线程编程

memcpy的多线程编程
EN

Stack Overflow用户
提问于 2013-03-21 14:56:23
回答 1查看 3.1K关注 0票数 3

我正在为memcpy函数做一个优化任务,我在这里找到了这个链接。How to increase performance of memcpy

因为我不熟悉多线程编程,所以我不知道如何将下面的代码插入到原始的main函数中?如何将原问题中的代码修改为多线程memcpy项目?我的意思是,如何为这个多线程memcpy项目创建一个完整的项目。在原始的主函数中插入startCopyThreadsstopCopyThreadsmt_memcpy函数等函数的位置在哪里?

代码语言:javascript
复制
#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;
}
EN

回答 1

Stack Overflow用户

发布于 2013-03-21 19:05:33

这在很大程度上取决于架构和操作系统。

使用一个处理器:

如果你在只有一个核心的机器上使用memcpy的线程,那么它不会显示加速。原因是,对于在一个处理器上运行的所有线程,都会有上下文切换,这与使用不使用线程的memcpy相比会有很大的开销。

使用多核:

在这种情况下,它还取决于内核,无论它是否将线程映射到不同的处理器上,因为这些线程将是用户级的。如果您的线程在不同的处理器上并发运行,那么如果内存具有双端口访问,您可能会看到加速。对于单端口访问,我不确定它是否会有所改善。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15541231

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档