将std :: map对象传递给线程

rob*_*obo 0 c++ multithreading pthreads thread-safety

我的代码试图传递一个std :: map作为线程的引用,但似乎有些不好并导致

error: invalid conversion from ‘void* (*)(std::map<std::basic_string<char>,
       std::vector<std::basic_string<char> > >)’ to ‘void* (*)(void*)’ [-fpermissive]
Run Code Online (Sandbox Code Playgroud)

我需要将map传递给线程并在该线程中插入map的键和值,并在成功之后.在主进程中,我需要更新或复制(线程映射)在同一映射的另一个对象,即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;  



}
Run Code Online (Sandbox Code Playgroud)

Lig*_*ica 5

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);
Run Code Online (Sandbox Code Playgroud)

...或者,更好的是,使用boost::thread(C++ 98)或std::thread(C++ 11及更高版本)来获得类型安全性和更长的使用寿命.你不是在写一个C程序.