简体   繁体   English

C语言中的多线程问题

[英]Multi-Threading Issue in C

I'm trying out Multi-threading in C for the first time, and I seem to be doing something wrong which I hope you could help me with. 我第一次尝试使用C进行多线程,但似乎做错了,希望您能为我提供帮助。 Here is my code: 这是我的代码:

#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;
}

In this code, Array "b" seems to populate fine, however Array "a" does not. 在此代码中,数组“ b”似乎可以很好地填充,但是数组“ a”却没有。 Sorry if the answer is something stupid! 抱歉,答案很愚蠢!

EDIT: I just tried again, and both arrays are all '0's. 编辑:我只是再次尝试,并且两个数组都是'0'。 Not quite sure what's going on. 不太确定发生了什么。 I'm using Visual Studio in case it's a debugging issue or something. 我正在使用Visual Studio,以防出现调试问题。

Cheers. 干杯。

The last parameter of WaitForMultipleObjects must be INFINITE , not 0 . WaitForMultipleObjects的最后一个参数必须为INFINITE而不是0 With 0 , the function returns immediatly. 如果为0 ,则函数立即返回。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM