【发布时间】:2017-06-27 19:44:54
【问题描述】:
Mycode 试图传递一个 std::map 作为对线程的引用,但似乎有些东西不好并导致
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;
}
【问题讨论】:
-
如果您可以访问 C++11 或更高版本,我建议您使用
std::thread而不是pthread_xxx。 -
pthread_create看起来是否理解std::reference_wrapper?
标签: c++ multithreading thread-safety pthreads