【发布时间】: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