我正在编写一个小试验项目,我需要将 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);
}
}
我想按值传递的原因是,每个线程池线程都有它自己的对象副本,因为指针被第一个函数从列表中删除,如果我通过引用传递,这将导致错误。