c - WIN32线程程序问题

标签 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);
}

最佳答案

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

DWORD WINAPI ThreadProc(
  _In_ LPVOID lpParameter
);

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

线程函数末尾没有 return 语句,因此这是未定义的行为。事实上,你的代码能够编译真是一个奇迹。整个多线程方法是不正确的,必须从头开始重新设计。

关于c - WIN32线程程序问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41234858/

相关文章:

c - 头文件中的函数原型(prototype)与定义不匹配,如何捕获?

c++ - Win32 : why does my PRINTDLG (or PRINTDLGEX) have gray background?

c++ - 如何拦截 "Show Desktop"事件?

c++ - 从线程执行的函数返回结构数组

C++ DLL - 跨线程回调

winapi - 如何在高 DPI 显示器上获得正常大小的光标?

c - 如何到达文件中特定行的开头?

c - 用 C 中的值初始化整个数组

c - GCC 的纯数据静态库

java - 如何取消从控制台读取输入?