[英]pass std::map object to thread
Mycode试图传递std :: map作为对线程的引用,但似乎有些不好并导致
error: invalid conversion from ‘void* (*)(std::map<std::basic_string<char>,
std::vector<std::basic_string<char> > >)’ to ‘void* (*)(void*)’ [-fpermissive]
我需要将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;
}
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);
…或者,更好的是,使用boost::thread
(C ++ 98)或std::thread
(C ++ 11及更高版本)来获得类型安全性和更长的使用寿命 。 您不是在编写C程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.