【问题标题】:Basic question in creating thread in C++在 C++ 中创建线程的基本问题
【发布时间】:2011-01-12 08:42:42
【问题描述】:

我有一个类成员函数A,它创建一个线程来运行另一个函数B。 FunctionB 将执行一些操作并在一段时间后停止(这是一种触发并忘记函数调用,所需的 functionA 调用和线程数将取决于运行时结果)。 FunctionA 将被多次调用。我意识到 pthread_create 将 pthread_t 作为第一个参数,并且 pthread_t 在创建线程时必须可用。所以,我不能像下面这样声明它是本地的。那么我在哪里可以声明 pthread_t?

void classA::functionA(int param)
{ 
   pthread_t t; //could not declare local because functionA might return and destroy t before thread being created.
   pthread_create(&t , NULL, functionB, param);
}

void functionB(int param)
{

}

【问题讨论】:

  • 即使t被销毁,对functionB的执行有何影响?
  • 我有时会遇到分段错误。所以我猜这是因为 t 在创建线程之前就被销毁了。

标签: c++ multithreading


【解决方案1】:

首先,您可以将您的pthread_t 放入堆栈:您的functionA 在这方面很好。 pthread_create 直接存储线程句柄,所以只要它返回句柄就有效。新创建的线程不一定开始执行,但这没关系,因为它不会触及那个句柄。

但是,您需要以某种方式管理您的线程。如果您没有明确创建分离的,那么您必须在您的句柄上调用pthread_join 或pthread_detach。如果您不打电话,那么您正在泄漏资源。如果这确实是一个“一劳永逸”的线程,那么您应该使用pthread_detach 来确保操作系统在线程完成时进行清理。

无论哪种方式,您都需要确保线程访问的对象比线程对它们的任何潜在访问寿命长(例如,在设置“我不再需要这些对象”标志之前不销毁它们)

【讨论】:

    【解决方案2】:

    你可以在栈上有一个pthread_t变量,这没有问题。

    您是否有理由不使用像 boost::thread 这样的线程包装器?它会让你的生活更轻松。 http://www.boost.org/doc/libs/1_45_0/doc/html/thread/thread_management.html

    另一件事是你不能只是触发并忘记一个线程,因为一旦你这样做了,就不能在另一个线程停止访问它之前销毁该对象。换句话说,对象的析构函数必须确保没有其他线程访问该对象。

    【讨论】:

      【解决方案3】:

      我不相信您有问题,因为在将新线程标识符写入t 之前pthread_create() 不会返回,因此根本不需要执行new pthread_t。当然,您需要检查来自pthread_create() 的返回。

      【讨论】:

        【解决方案4】:

        我会这样做:

        class classA
        {
            void functionA();
            static void void functionB(classA* aThis);
        };
        
        void classA::functionA(int param)
        { 
        //create thread: note that this way pthread_t can even become the class-member 
        }
        
        void classA::functionB(classA* aThis)
        {
            classA* theThis = static_cast<classA*>(aThis);
            //now you can access classA members here easily
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-01-27
          • 2016-12-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多