我想模拟同时写入条件下stl map的异常行为。在这里,我使用单个映射并同时从多个线程插入数据。由于我们只使用一个地图对象,因此它不应该允许。请通过以下示例代码
#include <iostream>
#include <map>
#include <iterator>
#include <algorithm>
extern "C"
{
#include <pthread.h>
#include <string.h>
#include <stdlib.h>
}
using namespace std;
//functor to print map
struct PrintMp
{
void operator()(pair<int,int> pr)
{
cout<<pr.first<<" => "<<pr.second<<endl;
}
};
//thread 1
//inserts continuous no from 0 to 4999
void* ins_th1(void *arg)
{
map<int, int> *mp = static_cast<map<int, int>* >(arg);
for(int i =0 ; i<5000; i++)
mp->insert(pair<int,int>(i, i+1000));
return NULL;
}
//thread 1
//inserts continuous no from 0 to 4999
void* ins_th2(void *arg)
{
map<int, int> *mp = static_cast<map<int,int>* >(arg);
for(int i=5000; i<10000; i++)
mp->insert(pair<int, int>(i, i+2000));
return NULL;
}
int main()
{
typedef map<int, int> IntMapType;
IntMapType mp;
PrintMp MpPrintObj;
int rc;
pthread_t th1, th2;
//thread 1 creation
rc = pthread_create(&th1, NULL, ins_th1, static_cast<void*>(&mp));
if ( rc != 0)
{
cerr<<strerror(rc)<<"in thread1"<<endl;
exit(EXIT_FAILURE);
}
//thread 2 creation
rc = pthread_create(&th2, NULL, ins_th2, static_cast<void*>(&mp));
if(rc!=0)
{
cerr<<strerror(rc)<<"in thread2"<<endl;
exit(EXIT_FAILURE);
}
//lets wait for the thread to finish
rc = pthread_join(th1, NULL);
if ( rc != 0)
{
cerr<<strerror(rc)<<"join failure for thread1"<<endl;
exit(EXIT_FAILURE);
}
rc = pthread_join(th2, NULL);
if ( rc != 0)
{
cerr<<strerror(rc)<<"join failure for thread2"<<endl;
exit(EXIT_FAILURE);
}
cout<<"Map data"<<endl;
//now print it
for_each(mp.begin(), mp.end(), MpPrintObj);
cout<<endl;
return 0;
}
但它不起作用。谁能建议我一些方法?