C++ Tutorial std::atomic

Letzte Änderung: 21.02.2016

Asynchrone Ausführung

Starten eines Thread und kontrollieren über std::atomic.

main.cpp
#include <unistd.h>

#include "producer.h"

//!
//! Use std::atomic to control a thread.
//! \li create a new Producer
//! \li start the Producer
//! \li let it run for 2 seconds
//! \li stop the Producer
//! \return 0
//!
int main(int, char**)
{
  Producer producer;
  producer.start();
  sleep(2);
  producer.stop();

  return 0;
}
producer.h
#ifndef TTN_CPP_TUTORIAL_TUTORIAL1_ATOMIC_PRODUCER_H
#define TTN_CPP_TUTORIAL_TUTORIAL1_ATOMIC_PRODUCER_H

#include <atomic>
#include <math.h>
#include <thread>

namespace // anonymous
{
    const int STATUS_STOPPED = 0;       //!< Producer is stopped
    const int STATUS_RUNNING = 1;       //!< Producer is running
    const int STATUS_CANCELING = 2;     //!< Producer is canceling run

}
class Producer
{
    private:
        int m_nextItemId;               //!< Id of next item to produce
        std::thread* m_worker;          //!< Worker thread
        std::atomic_int m_status;       //!< Current status of Producer

    public:
        //!
        //! Constructor
        //!
        Producer()
            : m_nextItemId(0)
            , m_worker(nullptr)
            , m_status(STATUS_STOPPED)
        {}

        //!
        //! Destructor
        //!
        ~Producer()
        {}

        //!
        //! Produce new items
        //!
        void produce()
        {
            double result = 0;
            while(m_status == STATUS_RUNNING) {
                ++m_nextItemId;
                for (int i = 0; i < 1000000; ++i) {
                    result = sqrt(i);
                }
                (void)result;
                printf("#");
                fflush(stdout);
            }
            m_status = STATUS_STOPPED;
            printf("nextItemId=%i\n", m_nextItemId);
            fflush(stdout);
        }

        //!
        //! Start produce asynchron
        //!
        void start()
        {
            int mSTATUS_STOPPED = STATUS_STOPPED;
            m_status.compare_exchange_strong(mSTATUS_STOPPED, STATUS_RUNNING);

            m_worker = new std::thread(&Producer::produce, this);
            m_worker->detach();
        }

        //!
        //! Stop of asynchron produce
        //!
        void stop()
        {
            int mSTATUS_RUNNING = STATUS_RUNNING;
            m_status.compare_exchange_strong(mSTATUS_RUNNING, STATUS_CANCELING);

            printf("\n");
            while (m_status == STATUS_CANCELING) {
                printf(".");
                fflush(stdout);
                usleep(100);
            }
            printf("\n");
            fflush(stdout);
        }
};

#endif // TTN_CPP_TUTORIAL_TUTORIAL1_ATOMIC_PRODUCER_H




© 2003-2017 th-thielemann.de