【问题标题】:Multi-Threading Issue in CC中的多线程问题
【发布时间】:2014-01-31 16:02:35
【问题描述】:

我第一次在 C 中尝试多线程,我似乎做错了什么,希望你能帮助我。这是我的代码:

#include "stdafx.h"

#define MAX_THREADS 2


int a[100000];
int b[200000];

void startThreads();

DWORD WINAPI populateArrayA(LPVOID data)
{
    int i;
    int* pA = (int*)data;

    for(i = 0; i < sizeof(a) / sizeof(int); i++)
    {
        *pA = i;
        pA++;
    }

    return 0;
}
DWORD WINAPI populateArrayB(LPVOID data)
{
    int i;
    int* pB = (int*)data;

    for(i = 0; i < sizeof(b) / sizeof(int); i++)
    {
        *pB = i;
        pB++;
    }
    return 0;
}

void startThreads()
{
    HANDLE threads[MAX_THREADS];
    DWORD  threadIDs[MAX_THREADS];

    threads[0] = CreateThread(NULL,0,populateArrayA,a,0,&threadIDs[0]);
    threads[1] = CreateThread(NULL,0,populateArrayB,b,0,&threadIDs[1]);

    if(threads[0] && threads[1])
    {
        printf("Threads Created. (IDs %d and %d)",threadIDs[0],threadIDs[1]);
    }

    WaitForMultipleObjects(MAX_THREADS,threads,true,0);

}

int main(int argc, char* argv[])
{
    int i;

    memset(a,0,sizeof(a));
    memset(b,0,sizeof(b));

    startThreads();

    return 0;
}

在这段代码中,数组“b”似乎填充得很好,但数组“a”没有。对不起,如果答案很愚蠢!

编辑:我又试了一次,两个数组都是'0'。不太清楚发生了什么。我正在使用 Visual Studio,以防它是调试问题之类的。

干杯。

【问题讨论】:

  • 那么a 最终会是什么样子?
  • 全 0,因为它们也已初始化。谢谢
  • 很奇怪。我刚刚通过 Visual Studio 2010 运行了这个确切的代码,它们看起来都很好。
  • 我刚刚又试了一次,两个数组都是'0'。不太清楚发生了什么。
  • 何时以及如何检查数组值?

标签: c multithreading winapi


【解决方案1】:

WaitForMultipleObjects的最后一个参数必须是INFINITE,而不是0。 使用0,函数立即返回。

【讨论】:

  • 完美。感谢您的帮助。
  • 奇怪的是,它仍然在我的系统上运行良好。也许我的处理器更快并且能够完成线程。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多