1

我正在编写一个小试验项目,我需要将 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);
    }

}

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

4

2 回答 2

2

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

于 2010-10-05T14:01:31.600 回答
1

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

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

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

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

于 2010-10-05T14:22:44.817 回答