按值将对象传递给另一个线程

时间:2010-10-05 13:48:11

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

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

出于某种原因,我似乎无法通过值传递我的项目到线程池线程...

有人可以帮助我做错了吗?

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);
    }

}

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

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

错误发生在运行时或编译时?

我创建自己的代码,没有编译错误。

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

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