[英]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.