동시 쓰기 조건에서 stl map의 비정상적인 동작을 시뮬레이트하고 싶습니다. 여기에서는 단일 맵을 사용하면서 동시에 여러 스레드에서 데이터를 삽입하고 있습니다. 하나의지도 개체 만 사용하므로 허용해서는 안됩니다. 다음 샘플 코드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;
}
통과하지만이 작동하지 않습니다하시기 바랍니다. 아무도 내게 어떤 접근 방식을 제안 할 수 있습니까?
그것이 작동하지 않는다는 것이 무엇을 의미합니까? 무슨 일이야? – anio
그것은 작동하지 않거나 _did_ 작동하며 예상하지 못했습니까? – Chad
나는 stl map이 쓰레드에 안전하지 않기 때문에 적절한 출력을 보이지 않기를 기대했다. 그러나 그 모든 것이 적절하다는 것을 보여줍니다. –