Beispiel #1
0
int main()
{
    typedef std::queue<char> Queue;
    LockObject<Queue> shared_queue;
    std::atomic<bool> quit;
    
    // producer adds items to the queue
    std::thread producer([&shared_queue, &quit]()
    {
        while (!quit)
        {
            Locker<Queue> lock = shared_queue.lock(); // locks the mutex        
            Queue & queue = lock.get();
            for (char c = ' '; c <= '~'; ++c)
            {
                queue.push(c);
            }
        }
    });
    
    // consumer thread removes items from the queue
    std::thread consumer([&shared_queue, &quit]()
    {
        while (!quit)
        {
            std::string current;
            {
                Locker<Queue> lock = shared_queue.lock(); // locks the mutex        
                Queue & queue = lock.get(); 
                if (queue.empty()) return;
                while (!queue.empty())
                {
                    current.push_back(std::move(queue.front()));
                    queue.pop();
                }
            }
            std::cout << current << '\n';
            current.clear();
        }
    });    
    
    std::this_thread::sleep_for(std::chrono::milliseconds(1));
    quit = true;
    producer.join();
    consumer.join();
}