Is there a set of Win32 API functions to manage synchronized queues?

后端 未结 1 2032
情深已故
情深已故 2020-12-12 01:16

I have a program with several worker threads, and a main thread that receives jobs. In the main thread I want to queue the jobs onto a synchronized queue, and have the worke

相关标签:
1条回答
  • 2020-12-12 02:13

    Windows doesn't provide exactly what you want. What it does provide is thread pools -- with these, you not only don't have to create the queue yourself, but you don't have to create or (directly) manage the threads either.

    Of course, synchronized queues do exist too, just not as part of Windows. One I wrote looks like this:

    #ifndef QUEUE_H_INCLUDED
    #define QUEUE_H_INCLUDED
    
    #include <windows.h>
    
    template<class T, unsigned max = 256>
    class queue { 
        HANDLE space_avail; // at least one slot empty
        HANDLE data_avail;  // at least one slot full
        CRITICAL_SECTION mutex; // protect buffer, in_pos, out_pos
    
        T buffer[max];
        long in_pos, out_pos;
    public:
        queue() : in_pos(0), out_pos(0) { 
            space_avail = CreateSemaphore(NULL, max, max, NULL);
            data_avail = CreateSemaphore(NULL, 0, max, NULL);
            InitializeCriticalSection(&mutex);
        }
    
        void push(T data) { 
            WaitForSingleObject(space_avail, INFINITE);       
            EnterCriticalSection(&mutex);
            buffer[in_pos] = data;
            in_pos = (in_pos + 1) % max;
            LeaveCriticalSection(&mutex);
            ReleaseSemaphore(data_avail, 1, NULL);
        }
    
        T pop() { 
            WaitForSingleObject(data_avail,INFINITE);
            EnterCriticalSection(&mutex);
            T retval = buffer[out_pos];
            out_pos = (out_pos + 1) % max;
            LeaveCriticalSection(&mutex);
            ReleaseSemaphore(space_avail, 1, NULL);
            return retval;
        }
    
        ~queue() { 
            DeleteCriticalSection(&mutex);
            CloseHandle(data_avail);
            CloseHandle(space_avail);
        }
    };
    
    #endif
    
    0 讨论(0)
提交回复
热议问题