几个线程的关键部分

时间:2018-03-31 07:13:21

标签: c multithreading critical-section

我正在尝试了解互斥锁,信号量和临界区,我遇到了最后一个问题。我写了一个小程序,它在不同的线程中打印数字,但我希望它们能够在不受其他线程干扰的情况下在行中打印5个数字。

为此,我使用了结构CRITICAL_SECTION及其功能。我初始化主线程中的关键部分(并在完成后删除它),进入我打印我的数字的周期中的暴击部分,并在我达到我的条件时尝试释放暴击部分。据我所知,当我执行此操作时,可以启动并锁定另一个线程以打印5个值,但它也可以是相同的线程。

我希望看到这个:

Thread 1: 0
Thread 1: 1
Thread 1: 2
Thread 1: 3
Thread 1: 4
Thread 2: 0
Thread 2: 1
Thread 2: 2
Thread 2: 3
Thread 2: 4
Thread 3: 0
Thread 3: 1
Thread 3: 2
Thread 3: 3
Thread 3: 4
Thread 2: 5
Thread 2: 6
Thread 2: 7
Thread 2: 8
Thread 2: 9

但是现在我看到只有一个线程打印0-9值,这就是全部。 我做错了什么?

这是我的代码:

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

#define THREAD_NUM          3
#define BASE_THREAD_NUM     1
#define COUNT               10

CRITICAL_SECTION critsection;

typedef struct DATA_ {
    INT threadNum;
    INT data[COUNT];
} DATA, *PDATA;

DWORD WINAPI PrintValsThread(LPVOID lpParam)
{
    DATA* pVal = (DATA*)lpParam;
    INT counter = 0;

    for (USHORT i = 0; i < COUNT; ++i) {
        if ((counter % 5) == 0)
            EnterCriticalSection(&critsection);

        pVal->data[i] = i;
        printf("Thread %d, i = %d\n", pVal->threadNum, pVal->data[i], counter);
        counter++;

        if ((counter % 5) == 0 && counter > 0)
            LeaveCriticalSection(&critsection);
    }
    return 0;
}

INT main(INT argc, WCHAR **argv)
{
    DATA* pVal[THREAD_NUM + 1];
    DWORD dwthreadNumArray[THREAD_NUM];
    HANDLE hThreadArray[THREAD_NUM];

    InitializeCriticalSection(&critsection);
    for (INT i = 0; i < THREAD_NUM; ++i) {
        pVal[i] = (DATA*)malloc(sizeof(DATA));
        if (pVal[i] == NULL) {
            printf("pVal[%d] == NULL\n", i);
            break;
        }
        pVal[i]->threadNum = BASE_THREAD_NUM + i;

        hThreadArray[i] = CreateThread(NULL, 0, PrintValsThread, pVal[i], 0, &dwthreadNumArray[i]);
        if (hThreadArray[i] == NULL) {
            printf("hThreadArray[%d] failed, error %d\n", i, GetLastError());
        break;
        }

    }

    INT wait = WaitForMultipleObjects(THREAD_NUM, hThreadArray, TRUE, INFINITE);
    if (wait == WAIT_FAILED)
        printf("The function WaitForMultipleObjects() has been failed\n");

    for (INT i = 0; i < THREAD_NUM; ++i) {
        if (pVal[i] != NULL)
            free(pVal[i]);
        CloseHandle(hThreadArray[i]);
    }

    DeleteCriticalSection(&critsection);
    printf("It's over\n");

    _getch();
    return 0;
}

1 个答案:

答案 0 :(得分:0)

这是问题的解决方案:

for (USHORT i = 0; i < COUNT; ++i) {
    if ((counter % 5) == 0)
        EnterCriticalSection(&critsection);

    pVal->data[i] = i;
    printf("Thread %d, i = %d\n", pVal->threadNum, pVal->data[i], counter);
    counter++;

    if ((counter % 5) == 0 && counter > 0)
        LeaveCriticalSection(&critsection);
}