VC ++线程死锁

时间:2011-02-20 01:10:42

标签: multithreading visual-c++ queue deadlock

以下程序陷入僵局。谁能告诉我为什么?

#include<cstdlib>
#include<windows.h>
#include<iostream>
using namespace std;

class CircularQueue
{
public:
    CircularQueue(int s)
    {
        size = s;
        array = (int*)malloc(sizeof(int) * size);
        head = tail = -1;
        InitializeCriticalSection(&critical_section);
    }

    CircularQueue(void)
    {
        size = default_size;
        array = (int*)malloc(sizeof(int) * size);
        head = tail = -1;
        InitializeCriticalSection(&critical_section);
    }

    void initialize(int s)
    {
        EnterCriticalSection(&critical_section);

        size = s;
        array = (int*)realloc(array, sizeof(int) * size);
        head = tail = -1;

        LeaveCriticalSection(&critical_section);
    }

    void enqueue(int n)
    {
        EnterCriticalSection(&critical_section);

        tail = (tail + 1) % size;
        array[tail] = n;

        LeaveCriticalSection(&critical_section);
    }

    int dequeue(void)
    {
        EnterCriticalSection(&critical_section);

        head = (head + 1) % size;
        return array[head];

        LeaveCriticalSection(&critical_section);
    }

private:
    int *array;
    int size;
    int head, tail;
    CRITICAL_SECTION critical_section;
    bool initialized;
    static const int default_size = 10;
};

DWORD WINAPI thread1(LPVOID param)
{
    CircularQueue* cqueue = (CircularQueue*)param;
    cqueue->enqueue(2);
    cout << cqueue->dequeue() << endl;

    return 0;
}

DWORD WINAPI thread2(LPVOID param)
{
    CircularQueue* cqueue = (CircularQueue*)param;
    cqueue->enqueue(3);
    cout << cqueue->dequeue() << endl;

    return 0;
}

int main(void)
{
    HANDLE thread1_handle;
    HANDLE thread2_handle;

    CircularQueue cqueue;
    HANDLE array[2];

    thread1_handle = CreateThread(NULL, 0, thread1, &cqueue, 0, NULL);

    thread2_handle = CreateThread(NULL, 0, thread2, &cqueue, 0, NULL);

    array[0] = thread1_handle;
    array[1] = thread2_handle;

    WaitForMultipleObjects(1, array, TRUE, INFINITE);

    CloseHandle(thread1_handle);
    CloseHandle(thread2_handle);

    printf("end\n");
    return 0;
}

1 个答案:

答案 0 :(得分:4)

dequeue()中,您在return来电之前有LeaveCriticalSection()声明。如果您将编译器警告提高了,它可能会告诉您这个!