将STD :: MAP对象传递到线程

pass std::map object to thread

本文关键字:线程 对象 STD MAP      更新时间:2023-10-16

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程序。