思勤无邪

上学时,因我年龄最小,个头也最小,上课时,就像大猩猩堆里的猴一般。如今,这猴偶尔也把最近的一些情况写在这里。

   :: 首页 :: 联系 :: 聚合  :: 管理
  132 Posts :: 1 Stories :: 178 Comments :: 0 Trackbacks

公告

     吾日常三省吾身,曰思、曰勤、曰无邪。

积分与排名

  • 积分 - 177197
  • 排名 - 144

最新随笔

最新评论

阅读排行榜

评论排行榜

    C++ 一般会在构造函数里分配资源,在析构函数里释放资源。但当程序/函数不正常退出时,C++ 不能保证析构函数会被调用,这时,可以利用异常,在程序/函数需要退出时,扔出异常,在异常处理里退出程序/函数,这样可以使在函数调用堆栈上构造的对象正确析构。
    示例代码(摘自advanced linux programming 4.3.2 Thread Cleanup in C++):
#include <pthread.h>
class ThreadExitException
{
public:
    /* Create an exception-signaling thread exit with RETURN_VALUE. */
    ThreadExitException (void* return_value)
    : thread_return_value_ (return_value)
    {
    }
    /* Actually exit the thread, using the return value provided in the constructor. */
    void* DoThreadExit ()
    {
        pthread_exit (thread_return_value_);
    }
private:
    /* The return value that will be used when exiting the thread. */
    void* thread_return_value_;
};

void do_some_work ()
{
    while (1) {
        /* Do some useful things here */

        if (should_exit_thread_immediately ())
            throw ThreadExitException (/* thread’s return value = */ NULL);
    }
}

void* thread_function (void*)
{
    try {
        do_some_work ();
    }
    catch (ThreadExitException ex) {
        /* Some function indicated that we should exit the thread. */
        ex.DoThreadExit ();
    }
    return NULL;
}



posted on 2010-06-06 09:21 思勤无邪 阅读(663) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理