Home > Mobile >  Use thread with shared memory
Use thread with shared memory

Time:03-15

I have an exe that writes data to shared memory than i read data from shared memory, i want to use std::thread when copy shared memory to different memory because writer exe does not stop writing.

When i use std::thread for copying shared memory,i pass memory structure as parameter than memory structure will be null in thread function, but when use the function normally, function memory structure will be as i expect. am i missed something or std::thread not useable for shared memory ?

struct Foo {
imgHeader imgHeader;
uint8_t imgBuf[12441600];
}

void memCpyFunc(uint8_t buf[12441600], std::list<uint8_t*>& bufferList) {

    uint8_t* ImgBuffer = new uint8_t[12441600];
    memcpy(ImgBuffer, buf, 12441600);
    bufferList.push_back(ImgBuffer);

}



int main(){
    Foo* foo;
    shmid = shmget(SHM_KEY, sizeof(Foo), 0666 | IPC_CREAT);
    foo = (Foo*)shmat(shmid, NULL, 0);
    std::list<uint8_t*> bufferList;
    memCpyFunc(foo->imgBuf, bufferList); //It works
    std::thread thread(&memCpyFunc, foo->imgBuf, std::ref(bufferList)); //Segmantation Fault
    //foo->imgBuf error: Cannot access memory at address 0x7ffff03b3078
    thread.detach();
    if (shmdt(foo) == -1) {
        perror("shmdt");

    }
}


I simply want to copy data from shared memory to different memory with thread.

CodePudding user response:

Okay, there are some problems with your code as written. First, main is almost certainly going to quit before the thread gets a chance to run. But even if this isn't main but is something else (and thus your program isn't trying to quit), then bufferList is going out of scope before your thread runs.

This is a time when Francois might be right about using thread->join(), although I normally disagree with him about that. There are times to detach and times to use join.

Are you sure the error is about the shared memory and not about bufferList?

I'd do this. First, I'd change the detach to a join, and then I'd stick debug statements in the function you're calling. The code should work as long as main doesn't return too fast.

  • Related