Skip to main content
gamedev.net
🔒 Locked

Logging Thread

Started by guangwang1983 Jan 25, 2008 at 5:52 AM 1 replies 900+ views
Original Post
guangwang1983
guangwang1983
Hi, in my program, I have a main thread doing underline logic and another thread logs decisions of logic to reduce the performance impact of file writing. However my problem is How can I pass my string of message from the main thread to log thread? I was trying to use PostThreadMessage, but the parameter in the PoastThreadMessage only takes a pointer, which mean I have to use "new" to create my string and delete it in a different thread. Any suggestion will be appreciated.
Evil Steve
Evil Steve
I'd push the message into a queue of std::strings that's mutex locked. std::string will handle the [de]allocation pretty efficiently. Or is this C or some other language
the_edd
the_edd
Perhaps something like this?

// entirely untestedclass log : boost::noncopyable{    public:        log(const std::string &filename) :            stop_(false),            filename_(filename),            thread_(boost::bind(&log::poll_queue, this))        {        }        ~log()        {            {                boost::mutex::scoped_lock lk(mtx_);                stop_ = true;                have_data_.notify_one();            }            thread_.join();        }        void write(const std::string &msg)        {            boost::mutex::scoped_lock lk(mtx_);            q_.push(msg);            have_data_.notify_one();        }    private:        void poll_queue() // throw()        {            boost::mutex::scoped_lock lk(mtx_);                        while (true)            {                while (!stop_ && q_.empty()) have_data_.wait(mtx_);                std::ofstream f(filename_.c_str(), std::ios::out | std::ios::app);                std::ostream_iterator<std::string> it(f);                std::copy(q_.begin(), q_.end(), it);                q_.clear();                                if (stop_) break;            }        }    private:        bool stop_;        std::string filename_;        boost::thread thread_;        boost::mutex mtx_;        boost::condition have_data_;        std::deque<std::string> q_;};int main(){    log lg;    lg.write("lalala\n");}


This is making explicit what Evil Steve said.

The file gets re-opened each time making it less likely that buffered data won't be lost if the app crashes, but I can see an argument for keeping it open continually.

EDIT: replaced explicit while loop with std::copy.

[Edited by - the_edd on January 25, 2008 7:12:34 PM]

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.