흐르는 시간의 블로그...

원래는 CPPJSON 라이브러리를 쓰다가...

어차피 POCO의 Logger를 사용하는 중이기 때문에 하나라도 줄이자라는 생각에...

Poco::JSON을 사용하기로 하였다.


그러나... 간단한 문제가 어려운 상황에 봉착하였다.

영문으로는 아래에다 질문을 올렸고 잘 아는 어떤분(?)이 좋은 댓글을 달아 줬다.

나도 알아낸바가 있지만 짧은 영어로 길게 설명하기 어려워... 여기다가 좀 더 달아본다.


Bad cast exception on poco-library when I tried to cast Int64


원래 소스코드는 저기가서 보시고...

수정한 소스코드는 아래에 있다.


stack overflow에서 지적된 부분의


첫번째는...

_object == NULL 로 비교하면 안된다는 부분이다.


두번째는

각 이름에 해당하는 부분들에 null 값이 올 수 있다는 점이다.

따라서 그 부분을 체크하지 않으면 exception이 발생한다.


세번째는

extract 대신 convert를 사용해야 한다는 점이다.

위의 링크에 가서 테스트에 사용한 bcodew값을 보면 서울 지역은 int 안쪽에 들어오고 다른 지역은 Int64를 사용해야 한다

"BCodeW"를 통해 가져온 값의 타입을 보면 Int 범위는 "i", Int64범위는 "l"을 보여준다.

extract는 해당하는 값의 레퍼런스를 가져오기 때문에 정확한 타입이 맞지 않으면 Bad Cast Exception을 발생시킨다.

Int64가 더 큰 범위임에서 자동 캐스팅이 발생하지 않는다.

큰 범위로 캐스팅해서 값을 가져오고자 한다면 convert를 사용하자.

// POCO JSON 사용
bool CUBIUtils::ParseAddressResult( llong& _BCodeW, char* _szPOI, char* _szJibun, char* _szAPIResult )
{
	JSON::Parser parser;
	try
	{
		formatlog( LOG_DEBUG, "CUBIUtils::%s(%d) AddrSrc: %s", __func__, __LINE__, _szAPIResult);

		JSON::Object::Ptr _object = parser.parse(_szAPIResult).extract();

		_BCodeW = 0;
		if ( _object->isNull("BCodeW"))
			formatlog( LOG_WARN, "CUBIUtils::%s(%d) BCodeW is NULL", __func__, __LINE__);
		else
			_BCodeW = _object->get("BCodeW").convert();

		if ( _object->isNull("poi"))
			formatlog( LOG_WARN, "CUBIUtils::%s(%d) poi is NULL", __func__, __LINE__);
		else
			strcpy( _szPOI, _object->get("poi").extract().c_str());

		if ( _object->isNull("jibun"))
			formatlog( LOG_WARN, "CUBIUtils::%s(%d) jibun is NULL", __func__, __LINE__);
		else
			strcpy( _szJibun, _object->get("jibun").extract().c_str());
	}
	catch(exception &e)
	{
		formatlog( LOG_ERROR, "CUBIUtils::%s(%d) JSON parsing Exception. %s", __func__, __LINE__, e.what());
		return false;
	}

	return true;
}

공유메모리에 STL Container를 사용하는 방법을 검색해보니...

역시나 Stack Overflow로 간다.


How to store stl objects in shared memory (C++)?


선택된 답에 보면 boost::interprocess를 사용하라 한다.

그 내용을 좀 보면 결국 앞쪽에서 본 allocator를 제작해야 함을 알 수 있다.


자세히 들어가보자.

...


Boost shared memory 에서 map 사용하기 allocator 이용해서


Chapter 14. Boost.Interprocess



관련하여 fork로 부모 프로세스와 자식프로세스간에 사용하는 예제

Using shared memory as a pool of unnamed memory blocks




개발 과정에서 알아낸 몇가지 사항과 이슈 사항을 적도록 한다.

  1. 공유 메모리를 생성하고 해당 인스턴스를 삭제해도 데이터는 접근 가능하다
  2. 위의 사항은 다중 프로세스나 다중 쓰레드에서 사용하는 내용을 이해한다면 당연한 부분이다.
  3. 적용하는 프로세스가 fork를 사용하기 때문에 불필요한 부담을 없애기 위해 공유 메모리와 맵을 구성하고 바로 삭제하였다
  4. 해당 공유 메모리와 맵을 사용하는데 있어 특이 사항이 있었다
  5. 사용처에서 managed_shared_memory와 find()를 통해 해당 map을 검색할 수 있다
  6. 문제는 managed_shared_memory 인스턴스가 삭제된다면 해당 맵 포인터는 유지하지만 데이터에 접근이 불가능하다
  7. 따라서 공유메모리 사용 클래스를 고려한다면 인스턴스를 통해 맵을 사용하는 동안에는 반드시 managed_shared_memory 를 유지해야 한다





관련하여 IBM 홈페이지에 재밋는 자료를 공유한다


IPC 및 MPI 라이브러리를 사용하여 Boost로 동시 프로그래밍


본글의 출처는 아래와 같다.

Creating STL Containers in Shared Memory


2003년에 작성된 아래의 글은 참고만 해야 할듯 하다.

현실적으로 저런 방식으로는 사용하기 어려울듯 하다.


아래의 부분은 자료가 없어질 경우를 대비하여 전체를 수집하여 올린다.



Creating STL Containers in Shared Memory


Shared memory is one of the IPC (interprocess communication) facilities available in every major version of Unix. It allows two or more processes to map the same set of physical-memory segments to their address space. Since the memory segments are common to all processes that are attached to them, the processes can communicate through the common data in the shared-memory segments. Thus, as the name implies, shared memory is a set of physical-memory segments that are shared among processes. When a process attaches to shared memory, it receives a pointer to the beginning of the shared segments; the process then can use the memory just like any other memory. Of course, care must be taken when a shared-memory segment is accessed or written to synchronize with another process that has access to the same physical memory.

Consider the following code, which works on most Unix systems:

//Get shared memory id
//shared memory key
const key_t ipckey = 24568;   
//shared memory permission; can be
//read and written by anybody
const int perm = 0666;
//shared memory segment size
size_t shmSize = 4096;
//Create shared memory if not
//already created with specified
//permission
int shmId = shmget
  (ipckey,shmSize,IPC_CREAT|perm);
if (shmId ==-1) {
  //Error
}

//Attach the shared memory segment

void* shmPtr = shmat(shmId,NULL,0);

struct commonData* dp =
  (struct commonData*)shmPtr;

//detach shared memory
shmdt(shmPtr);

Types of Data Structures in Shared Memory

Care must be taken when placing data in shared memory. Consider the following structure:

Struct commonData {
  int sharedInt;
  float  sharedFloat;
  char* name;
Struct CommonData* next;
};
Process A does the following:

//Attach shared memory
struct commonData* dp =
  (struct commonData*) shmat
    (shmId,NULL,0);

dp->sharedInt = 5;
.
.
dp->name = new char [20];
strcpy(dp->name,"My Name");

dp->next = new struct commonData();
Some time later, process B does the following:

struct commonData* dp =
  (struct commonData*) shmat
    (shmId,NULL,0);

//count = 5;
int count = dp->sharedInt;
//problem
printf("name = [%s]\n",dp->name);
dp = dp->next;  //problem
Data members name and next of commonData are allocated from the heap in process A's address space. name and next are pointing to an area of memory that is only accessible by process A. When process B accesses dp->name or dp->next, it will cause a memory violation since it is accessing a memory area outside of its address space. At the minimum, process B will get garbage for the name and next values. Thus all pointers in shared memory should point to locations within shared memory. (That is why C++ classes that contain virtual function tables -- those that inherit from classes that have virtual member functions cannot be placed in shared memory -- is another topic.)

As a result of these restrictions, data structures designed to be used in shared memory usually tend to be simple.

C++ STL Containers in Shared Memory

Imagine placing STL containers, such as maps, vectors, lists, etc., in shared memory. Placing such powerful generic data structures in shared memory equips processes using shared memory for IPC with a powerful tool. No special data structures need to be designed and developed for communication through shared memory. In addition, the full range of STL's flexibility can be used as an IPC mechanism. STL containers manage their own memory under the covers. When an item is inserted into an STL list, the list container automatically allocates memory for internal data structures to hold the inserted item.

Consider placing an STL container in shared memory. The container itself allocates its internal data structure. It is an impossible task to construct an STL container on the heap, copy the container into shared memory, and guarantee that all the container's internal memory is pointing to the shared-memory area.

Process A does the following:

//Attach to shared memory
void* rp = (void*)shmat(shmId,NULL,0);
//Construct the vector in shared
//memory using placement new
vector<int>* vpInA = new(rp) vector<int>*;
//The vector is allocating internal data
//from the heap in process A's address
//space to hold the integer value
(*vpInA)[0] = 22;
Process B does the following:

vector<int>* vpInB =
  (vector<int>*) shmat(shmId,NULL,0);

//problem - the vector contains internal 
//pointers allocated in process A's address 
//space and are invalid here 
int i = *(vpInB)[0];

C++ STL Allocators to the Rescue

One of the type arguments to an STL container template is an allocator class. The allocator class is an abstraction of a memory-allocation model. The default allocator allocates memory from the heap. The following is a partial definition of the vector class in STL:

template<class T, class A = allocator<T> >
  class vector {
    //other stuff
};
Consider the following declaration:

//User supplied allocator myAlloc
vector<int,myAlloc<int> > alocV;  
Assume myAlloc<int> allocates memory from shared memory. The vectoralocV is constructed entirely from shared-memory space.

Process A does the following:

//Attach to shared memory
void* rp = (void*)shmat(shmId,NULL,0);
//Construct the vector in shared memory
//using placement new
vector<int>* vpInA =
  new(rp) vector<int,myAlloc<int>>*;
//The vector uses myAlloc<int> to allocate
//memory for its internal data structure
//from shared memory
(*v)[0] = 22;
Process B does the following:

vector<int>* vpInB =
  (vector<int,myAlloc<int> >*) shmat
    (shmId,NULL,0);

//Okay since all of the vector is
//in shared memory
int i = *(vpInB)[0];
All processes attached to the shared memory may use the vector safely. In this case, all memory allocated to support the class is allocated from the shared memory, which is accessible to all the processes. By supplying a user-defined allocator, an STL container can be placed in shared memory safely.

A Shared Memory Based STL Allocator

Listing 1 shows an implementation of the C++ Standard STL allocator. The STL allocator is itself a template. The Pool class does the shared-memory allocation and deallocation.

Listing 2 shows the Pool class definition. Pool's static member shm_ is of type shmPool. There is a single instance of shmPool per process, and it represents shared memory.shmPool's constructor creates and attaches the desired size of shared memory. Shared-memory parameters, such as the shared-memory key, number of shared-memory segments, and size of each segment, are passed to the shmPool class constructor through environmental variables. The data member segs_ is the number of shared-memory segments; segSize_ is the size of each shared-memory segment. The path_ and key_ data members are used to create a unique ipckeyshmPool creates one semaphore for each shared segment to synchronize memory-management activities among processes attached to the shared-memory segment. shmPool constructs a Chunk class in each of the shared-memory segments. Chunkrepresents a shared-memory segment. For each shared-memory segment, the shared-memory identifier shmId_, a semaphore semId_ to control access to the segment, and a pointer to the Link structure that represents the free list are kept in the Chunk class.

Placing an STL Container in Shared Memory

Suppose process A places several STL containers in shared memory. How does process B find these containers in shared memory? One way is for process A to place the containers at fixed offsets in the shared memory. Process B then can go to the specified addresses to obtain the containers. A cleaner way is for process A to create an STL map in shared memory at a known address. Then process A can create containers anywhere in shared memory and store the pointers to the containers in the map using a name as a key to the map. Process B knows how to get to the map since it is at an agreed location in shared memory. Once process B obtains the map, it can use the containers' names to get the containers. Listing 3 shows a container factory. The Pool class method's setContainer places the map at a well-known address. The getContainer method returns the map. The factory's methods are used to create, retrieve, and remove containers from shared memory. The container types passed to the container factory should haveSharedAllocator as their allocator.

Conclusion

The scheme described here can be used to create STL containers in shared memory. The total size of shared memory (segs_* segSize_) should be large enough to accommodate the STL container's largest size, since Pooldoes not create new shared memory if it runs out of space.

The complete source code is available for download at <www.cuj.com/code>.


References

Bjarne Stroustrup. The C++ Programming Language, Third Edition (Addison-Wesley, 1997).

Matthew H. Austern. Generic Programming and the STL: Using and Extending the C++ Standard Template Library (Addison-Wesley, 1999).

About the Author

Grum Ketema has Masters degrees in Electrical Engineering and Computer Science. With 17 years of experience in software development, he has been using C since 1985, C++ since 1988, and Java since 1997. He has worked at AT&T Bell Labs, TASC, Massachusetts Institute of Technology, SWIFT, BEA Systems, and Northrop.



Listing 1: An implementation of the C++ Standard STL allocator

template<class T>class SharedAllocator {
    private:
        Pool pool_;    // pool of elements of sizeof(T)
    public:
        typedef T value_type;
        typedef unsigned int  size_type;
        typedef ptrdiff_t difference_type;
        typedef T* pointer;
        typedef const T* const_pointer;
        typedef T& reference;
        typedef const T& const_reference;
        pointer address(reference r) const { return &r; }
        const_pointer address(const_reference r) const {return &r;}
        SharedAllocator() throw():pool_(sizeof(T)) {}
        template<class U> SharedAllocator
            (const SharedAllocator<U>& t) throw():
                        pool_(sizeof(T)) {}
        ~SharedAllocator() throw() {};
        // space for n Ts
        pointer allocate(size_t n, const void* hint=0)
        {
            return(static_cast<pointer> (pool_.alloc(n)));
        }
        // deallocate n Ts, don't destroy
        void deallocate(pointer p,size_type n)
        {
            pool_.free((void*)p,n);
            return;
        }
        // initialize *p by val
        void construct(pointer p, const T& val) { new(p) T(val); }
        // destroy *p but don't deallocate
        void destroy(pointer p) { p->~T(); }
        size_type max_size() const throw()
        {
            pool_.maxSize();
        }
        template<class U>    
        // in effect: typedef SharedAllocator<U> other
        struct rebind { typedef SharedAllocator<U> other; };
};

template<class T>bool operator==(const SharedAllocator<T>& a,
    const SharedAllocator<T>& b) throw()
{
        return(a.pool_ == b.pool_);
}
template<class T>bool operator!=(const SharedAllocator<T>& a,
    const SharedAllocator<T>& b) throw()
{
        return(!(a.pool_ == b.pool_));
}

Listing 2: The Pool class definition

class Pool {
    private:
        class shmPool {
            private:
                struct Container {
                    containerMap* cont;
                };
                class Chunk {
                    public:
                        Chunk()
                        Chunk(Chunk&);
                        ~Chunk() {}
                        void* alloc(size_t size);
                        void free (void* p,size_t size);
                    private:
                        int shmId_;
                        int semId_;
                        int lock_()
                };
                int key_;
                char* path_;
                Chunk** chunks_;
                size_t segs_;
                size_t segSize_;
                Container* contPtr_;
                int contSemId_;
            public:
                shmPool();
                ~shmPool();
                size_t maxSize();
                void* alloc(size_t size);
                void free(void* p, size_t size);
                int shmPool::lockContainer()
                int unLockContainer()
                containerMap* getContainer()
                void shmPool::setContainer(containerMap* container)
        };

    private:
        static shmPool shm_;
        size_t elemSize_;
    public:
        Pool(size_t elemSize);
        ~Pool() {}
        size_t maxSize();
        void* alloc(size_t size);
        void free(void* p, size_t size);
        int lockContainer();
        int unLockContainer();
        containerMap* getContainer();
        void setContainer(containerMap* container);
};
inline bool operator==(const Pool& a,const Pool& b)
{
    return(a.compare(b));
}


Listing 3: A container factory

struct keyComp {
    bool operator()(const char* key1,const char* key2)
    {
        return(strcmp(key1,key2)<0);
    }
};
class containerMap: public map<char*,void*,keyComp,SharedAllocator<char* > > {};
class containerFactory {
    public:
        containerFactory():pool_(sizeof(containerMap)){}
        ~containerFactory() {}
        template<class Container> Container* createContainer
            (char* key,Container* c=NULL);
        template<class Container> Container* getContainer
            (char* key,Container* c=NULL);
        template<class Container> int removeContainer
            (char* key,Container* c=NULL); 
    private:
        Pool pool_;
        int lock_();
        int unlock_();
};


현재 TCP를 통해 수신한 데이터를 처리하는 업무를 하고 있다.


프로그램의 구조는 크게 "수신단" 과 "처리단"으로 분리하여 처리한다.

하나의 프로그램 내에서 두개의 모듈로 나누는 방법과 두개의 프로그램으로 나누는 방법의 두가지를 고민하였다.


현재의 업무 요구사항은 수신데이터의 처리만을 제공한다.

그 데이터의 처리 결과를 반환하거나 할 필요가 없으며 반환할 수도 없다.


프로그램 구성의 단순화를 위해 수신단 프로그램(listener)와 처리단 프로그램(proc 혹은 finisher)로 구분하였다.


두개의 프로그램 간에는 공유메모리와 세마포를 사용하여 데이터를 주고 받는다.


수신단은 TCP 수신과 수신한 패킷을 여러 곳으로 분배하는 기능을 가진다.

처리단은 수신한 패킷을 데이터베이스에 저장하고 관련된 실질적인 업무를 처리하는 기능을 가진다.


처리단의 경우 업무 로직과 관련한 다양한 데이터를 메모리에 올리고 관리해야 했다.

따라서 쓰레드 방식으로 처리하고 관련 데이터는 전역으로 유지하도록 하였다.


수신단의 경우에는 단순 처리작업이므로 메모리를 많이 사용할 염려도 없으며 

특수한 경우 혹은 오류 상황에서 에러 범위를 최소화할 필요가 있다.

fork를 사용하여 프로세스를 늘리는 방식을 사용하였다.


최근 수신단에 추가 요구사항이 발생하였다.

수신 데이터 별로 분리하여 각기 다른 곳으로 발송해야 하는 이슈이다.

이 경우 초기에 데몬이 메모리상에 설정 데이터를 가지고 작업을 진행할 수 있다.


그러나 fork 방식의 경우 메모리까지 복제를 진행하므로 설정이 커질 경우 여러 이슈가 발생할 수 있다.

이에 따라 공유 메모리를 할당하고 그 공유메모리에 STL Container를 적용시켜 사용하는 방법을 고려하였다.


각 프로세스에서 공유메모리를 접근하는 경우 동시성 문제만 제외한다면 추가적인 부담은 거의 없는 편이다.

현재의 요구사항은 초기데몬에서 해당 메모리를 구축하면 나머지 프로세스들은 단순 읽기만을 수행한다.

동시성 문제가 발생하지 않는다.


물론 search 기능과 같은 경우 내부적인 전역변수의 문제로 동시성 문제가 발생할 수도 있다.

이 경우는 반드시 확인해야할 이슈이다.


선제적으로 확인해야 할 것은 STL Container를 공유메모리에 구축할 수 있는 것인가 하는 부분이다.


이와 관련된 자료를 찾았다.

다수의 프로세스에서 전역메모리를 공유하는 방식으로 생각해도 될 것이다.


관련 자료는 다음 포스트에서 보도록 하자.

...


ps. 공유메모리를 직접 관리하고 BTree를 구축하는 방법도 고려하였으나 구현 자체보다는 혹여 있을 버그를 고려하여 참았다.