Reputation: 23
Mycode is trying to pass a std::map as reference to thread but it seems something is bad and result in
error: invalid conversion from ‘void* (*)(std::map<std::basic_string<char>,
std::vector<std::basic_string<char> > >)’ to ‘void* (*)(void*)’ [-fpermissive]
I need to pass map to thread and insert the key and value of map in that thread and after successful. In main process i need to update or copy(thread map) in another object of same map i.e 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;
}
Upvotes: 0
Views: 1091
Reputation: 385098
pthread_create
is not a template, and it does not understand C++ types. It takes a void*
, which is what C libraries do in order to fake templates (kind of).
You can pass a casted pointer instead of a C++ reference wrapper object:
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);
…or, better yet, use boost::thread
(C++98) or std::thread
(C++11 and later) to get type safety and a longer lifespan. You're not writing a C program.
Upvotes: 5