【问题标题】:pass object by value to another thread按值传递对象到另一个线程
【发布时间】:2010-10-05 13:48:10
【问题描述】:

我正在编写一个小试验项目,我需要将 QueuList 类型的对象按值传递给线程池线程。它是一个 Boost 线程池,我正在使用 Bind 将参数传递给线程。

由于某种原因,我似乎无法将我的项目按值传递给线程池线程...

谁能帮助我做错了什么?

void ConsumerScheduler()
{
    int count = 0;
    typedef boost::intrusive::list<QueuList> List;
    while (true)
    {
        WaitForSingleObject(hConsumer, 2000); // Wait for hConsomuer to become > 0
        {
            //lock Queue
            QueuList *item = NULL;
            boost::mutex::scoped_lock lock(mtx);
            {//Scope of lock
                if (lst->size() == 0)
                {
                    printf("List is emtpy"); 
                    continue;
                }
                else
                {
                    List::iterator iter(lst->begin());
                    item = &*iter;
                    lst->pop_front();  //Item is removed from list, so pointer is no longer available!!!
                    printf("Popped item off list.  List current size: %d\n",lst->size());
                    count++;
                }
            }
            //Pass to threadpool
            tpp.schedule(boost::bind(taskfunc,*item)); //it will not accept *item or item in this bind function to pass it by value
            total--;
            if (total == 0)
            {
                printf("Total is now zero!\nCount is %d\n", count);
            }
            if (count == 5)
                break;

            ReleaseSemaphore(hProducer,total , NULL);  // Release the hProducer semaphore, possibly waking producer
        }
    }
}

//Thread pool thread function
void taskfunc(QueuList list)
{
    boost::mutex::scoped_lock lock(mtx);
    {
        std::string name= list.GetName();
        printf("Name gotten: %s",name);
    }

}

我想通过值传递的原因是每个线程池线程都有它自己的对象副本,因为指针被第一个函数从列表中删除,如果我通过引用传递,这将导致错误。

【问题讨论】:

  • 请说明tpp是如何定义的以及编译器输出

标签: c++ multithreading pass-by-value


【解决方案1】:

您可以通过在队列和线程池调度中使用boost::shared_ptr&lt;QueueList&gt; 来解决这个问题。在某些 STL 中没有 unique_ptr 的情况下,这最能表达您想要的共享数据的移交。

【讨论】:

  • 实际上并没有:shared_ptr 是关于共享所有权,唯一表示单实例切换的标准智能指针是unique_ptr,并且尚未在所有 STL 中可用。 shared_ptr 是目前最差的替代品。
  • @Matthieu - 我认为最好提供一个得到广泛支持的解决方案以避免混淆
  • 我同意解决方案很好,但我会修改“表示单实例移交”评论。从语义上讲,共享和单身并没有真正混合。
【解决方案2】:

错误发生在运行时还是编译时?

我创建了自己的代码并且没有编译错误。

我不使用 boost,但是,如果您在运行时遇到错误,我认为错误是在作用域锁中。作用域锁不应该在括号内吗?

编辑:我没有发表评论的权限,所以我发布为答案

【讨论】:

  • 什么错误?你实现了 QueuList 的拷贝构造函数了吗?
  • 我知道boost::mutex::scoped_lock lock(mtx); 应该放在范围内,而不是在范围之上,正如@Bruno Caponi 所说。
猜你喜欢
  • 1970-01-01
  • 2013-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-24
  • 2015-06-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多