[英]Multi-Threading Issue in C
我第一次嘗試使用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,以防出現調試問題。
干杯。
WaitForMultipleObjects
的最后一個參數必須為INFINITE
而不是0
。 如果為0
,則函數立即返回。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.