WIN32线程程序问题

时间:2016-12-20 04:21:58

标签: c multithreading winapi

这是我第一次处理线程。

当我在没有GetCurrentThreadId()功能的情况下运行程序时,它会毫无问题地执行。

当我添加那行代码时,它仍会执行但是一旦到达结尾就会崩溃。这是为什么?

#include <Windows.h>
#include <stdio.h>
#include <conio.h>


static int tix[500];
static int done = 0;
HANDLE ghSemaphore;

DWORD WINAPI ThreadFunction();

int main(void)
{
    DWORD threadID1, threadID2, threadID3, threadID4;
    HANDLE hThread1, hThread2, hThread3, hThread4;

    for (int i = 0; i < 500; i++) //initialize array
    {
        tix[i] = 0;
    }

    ghSemaphore = CreateSemaphore(NULL, 1, 10, NULL);

    hThread1 = CreateThread(NULL, 0, ThreadFunction, NULL, 0, &threadID1);
    hThread2 = CreateThread(NULL, 0, ThreadFunction, NULL, 0, &threadID2);
    hThread3 = CreateThread(NULL, 0, ThreadFunction, NULL, 0, &threadID3);
    hThread4 = CreateThread(NULL, 0, ThreadFunction, NULL, 0, &threadID4);

    //printf("The thread ID: %d.\n", threadID1);
    //printf("The thread ID: %d.\n", threadID2);
    //printf("The thread ID: %d.\n", threadID3);
    //printf("The thread ID: %d.\n", threadID4);

    if (done = 1)
    {
        CloseHandle(hThread1);
        CloseHandle(hThread2);
        CloseHandle(hThread3);
        CloseHandle(hThread4);
    }

    for (int j = 0; j < 500; j++)
    {
        if (tix[j] = 0)
        {
            printf("not sold");
        }
        else if (tix[j] = 1)
        {
            printf("sold");
        }
    }

    return 0;
}

DWORD WINAPI ThreadFunction()
{
    WaitForSingleObject(ghSemaphore, 0);

    printf("current thread running : %d\n", GetCurrentThreadId());

    int i = 0;
    if (done != 0) // if loop to test wether or not the array is full
    {
        while (tix[i] = 1) //traverse the array to find a open spot
        {
            i++;
        }
        tix[i] = 1;

    }
    if (i == 499) //if i is 499, set test variable to 1
    {
        done = 1;
        return 0;
    }

    ReleaseSemaphore(ghSemaphore, 1, NULL);
}

1 个答案:

答案 0 :(得分:0)

您的线程功能签名不正确。线程采用一个PVOID上下文参数:

DWORD WINAPI ThreadProc(
  _In_ LPVOID lpParameter
);

您的线程可以在不释放信号量的情况下退出。此外,由于您使用一个值初始化它,该值大于线程数量并且从不检查WaitForSingleObject结果,因此不提供同步,并且多个线程将以不一致的方式修改共享缓冲区。更糟糕的是 - 没有什么能阻止你的程序主线程先前退出,而不是ThreadFunction

在线程函数的末尾没有return语句,因此这是一个未定义的行为。实际上,您的代码甚至可以编译,这是一个奇迹。这种多线程的整个方法是不正确的,必须从头开始重新编译。