gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:09:45 24 4
gpt4 key购买 nike

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

}

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

最佳答案

您可以使用 boost::shared_ptr<QueueList> 解决此问题在队列和线程池调度中。在没有 unique_ptr 的情况下,这最好地表达了您想要的共享数据的传递。在一些 STL 中。

关于c++ - 按值将对象传递给另一个线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3864226/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com