Boost :: stream exit code?

What is the standard way to get exit code from boost :: thread?
Documents do not touch on this topic at all.

+3
source share
3 answers

I do not know that the stream exit code is available as a specific operating system. You could simulate passing an exit code or a result code by doing something like this:

struct callable {
    int result;
    void operator()()
    {
        result = 42;
    }
};

void process_on_thread() {
    callable x;
    boost::thread processor(x);

    processor.join();
    int result = x.result;
}
-1
source

POSIX . : ++ 11 ++, Boost.Thread 1.41. , , , .

+5

Boost.Thread , , David . :

  • . .
  • If you create only one stream from a specific functor, then the functor may contain a common intelligent pointer to dynamically allocated existing code, which can then be read by the original functor object.

The following are examples of each method:

Method 1:

#include <boost/thread/thread.hpp>
#include <boost/thread/xtime.hpp>
#include <boost/shared_ptr.hpp>

#include <iostream>

struct thread_alarm
{
    thread_alarm(int secs, int &ec) : m_secs(secs), exit_code(ec) {  }
    void operator()()
    {
        boost::xtime xt;
        boost::xtime_get(&xt, boost::TIME_UTC);
        xt.sec += m_secs;

        boost::thread::sleep(xt);

        std::cout << "alarm sounded..." << std::endl;

        exit_code = 0xDEADBEEF;
    }

    int m_secs;
    int &exit_code;
};

typedef boost::shared_ptr<boost::thread> BoostThreadPtr;

int main(int argc, char* argv[])
{
    int secs = 1;
    int exit_codes[10];

    BoostThreadPtr threads[10];

    for (int i = 0; i<10; ++i) {
        std::cout << "setting alarm for 1 seconds..." << std::endl;
        thread_alarm alarm(secs, exit_codes[i]);
        threads[i] = BoostThreadPtr(new boost::thread(alarm));
    }

    for (int i = 0; i<10; ++i) {
        threads[i]->join();
        std::cout << "exit code == 0x" << std::hex << exit_codes[i] << std::endl;
    }
}

Method 2:

#include <boost/thread/thread.hpp>
#include <boost/thread/xtime.hpp>
#include <boost/shared_ptr.hpp>

#include <iostream>

struct thread_alarm
{
    thread_alarm(int secs) : m_secs(secs) { exit_code = IntPtr( new int(0) ); }
    void operator()()
    {
        boost::xtime xt;
        boost::xtime_get(&xt, boost::TIME_UTC);
        xt.sec += m_secs;

        boost::thread::sleep(xt);

        std::cout << "alarm sounded..." << std::endl;

        *exit_code = 0xDEADBEEF;
    }

    int m_secs;

    typedef boost::shared_ptr<int> IntPtr;
    IntPtr exit_code;
};

int main(int argc, char* argv[])
{
    int secs = 5;
    std::cout << "setting alarm for 5 seconds..." << std::endl;
    thread_alarm alarm(secs);
    boost::thread thrd(alarm);
    thrd.join();
    std::cout << "exit code == 0x" << std::hex << *(alarm.exit_code) << std::endl;
}
+1
source

Source: https://habr.com/ru/post/1722600/


All Articles