将STD :: MAP对象传递到线程
pass std::map object to thread
mycode试图通过std ::映射作为引用线程,但似乎有些不好,并且导致
error: invalid conversion from ‘void* (*)(std::map<std::basic_string<char>,
std::vector<std::basic_string<char> > >)’ to ‘void* (*)(void*)’ [-fpermissive]
我需要通过映射到线程并插入该线程和成功之后地图的密钥和值。在主要过程中,我需要在同一地图的另一个对象中更新或复制(线程映射(,即mymapcache
int main()
{
std::map< std::pair<std::string , std::string> , std::vector<std::string> > myMap,myMapCache;
pthread_t threads;
//how to pass map object in thread as reference
int rc = pthread_create(&threads, NULL, myfunction, std::ref(myMap));
if (rc)
{
cout << "Error:unable to create thread," << rc << endl;
exit(-1);
}
// if true then update to local myMapCache
if(update)
{
std::copy(myMap.begin(), myMap.end(), std::inserter(MyMapCache, myMapCache.end()) );
}
}
void * myfunction (std::map< std::pair<std::string , std::string> , std::vector<std::string> >& myMap)
{
// here i will insert data in a map
myMap[std::make_pair(key1,key2)].push_back(value);
// if update make the flag true
Update=true;
}
pthread_create
不是模板,也不了解C 类型。它需要一个void*
,这是C库为伪造模板(一种(。
您可以通过铸造的指针而不是C 参考包装对象:
int rc = pthread_create(&threads, NULL, myfunction, static_cast<void*>(&myMap));
// ...
void* myfunction(void* arg)
{
using T = std::map<std::pair<std::string, std::string>, std::vector<std::string>>;
T& myMap = *static_cast<T*>(arg);
&hellip;或者更好的是,使用boost::thread
(C 98(或std::thread
(C 11及以后(获得类型安全性和更长的寿命。您不是在编写C程序。
相关文章:
- 即发即弃 std::线程对象清理自身
- C++:处理线程本地对象销毁
- 结束另一个线程中使用的对象的生存期
- 将对象传递给多线程对象 Qt
- 运行线程和线程对象之间的关系
- 从从可调用参数创建的线程对象参数移动构造 C++11 线程
- 如何通过id获取线程对象?
- 线程对象函数 C++
- 关闭MFC对话框时多线程对象被破坏
- 线程对象的 WaitForSingleObject 在 DLL 卸载中不起作用
- 是否可以获取主线程的线程对象,并用它“join()”
- 如何在 C++11 中创建线程对象数组
- 如何在线程本身终止时删除提升线程对象
- 提升线程工作线程对象在线程完成后的重用
- 多线程对象中的堆损坏
- 从另一个对象指向线程对象:危险
- Qt 在另一个线程中排队工作线程对象的退出事件
- 线程对象在创建后立即销毁自身
- visual studio 2010 -是否有办法在旧的C/ c++编译器中使用c++ 11线程对象?
- 在c++中,两个线程/对象在一个对象集合中可以安全地做什么?