我写一个小试验项目,我需要按值传递和类型QueuList对象的线程池线程。它是一个升压线程池,我使用绑定到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);
    }

}

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

有帮助吗?

解决方案

可以通过在队列中,线程池调度使用boost::shared_ptr<QueueList>解决这个问题。该越区切换的共享数据的要最好表示,在一些补充交易没有unique_ptr的。

其他提示

在运行时或编译时会出现错误?

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

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

编辑:我没有权限来评论,所以我张贴的答案

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top