简体   繁体   中英

Passing a struct to a thread, how access multiple data in struct?

I have a problem. I need to use a struct of OpenCV Mat images for passing multiple arguments to a thread.

I have a struct like this:

struct Args
{
    Mat in[6];
    Mat out[6];
};

And a void function called by thread, like this:

void grey (void *param){
    while (TRUE)
    {
    WaitForSingleObject(mutex,INFINITE);
    Args* arg = (Args*)param;
    cvtColor(*arg->in,*arg->out,CV_BGR2GRAY);
    ReleaseMutex(mutex);
    _endthread();
    }
}

For launch the grey function as thread with two Mat array arguments, I use the follow line in main:

Args dati;
    *dati.in = *inn;
    *dati.out = *ou;


handle1 = (HANDLE) _beginthread(grey,0,&dati);

Now, my problem is: I need to access to all 6 elements of two array "in" and "out" in struct passed to thread from thread itself or however, find a mode to shift array from 0 to 5 to elaborate all elements with the "grey" functions.

How can I do this from thread or from main? I mean using grey function for elaborate all 6 elements of array Mat in[6] of struct Args that I pass to thread in that mode.

Can someone help me or gime me an idea? I don't know how do this.

Before you create the thread, you assign the array like this:

*dati.in = *inn;
*dati.out = *ou;

This will only assign the first entry in the array. The rest of the array will be untouched.

You need to copy all of the source array into the destination array. You can use std::copy for this:

std::copy(std::begin(dati.in), std::end(dati.in), std::begin(inn));

Of course, that requires that the source "array" inn contains at least as many items as the destination array.

Then in the thread simply loop over the items:

for (int i = 0; i < 6; i++)
{
    cvtColor(arg->in[i], arg->out[i], CV_BGR2GRAY);
}

When you launch your thread, this code:

Args dati;
*dati.in = *inn;
*dati.out = *ou;

is only initialising one of the six elements. If inn and ou are actually 6 element arrays, you will need a loop to initialise all 6.

Args dati;
for (int i = 0; i < 6; i++) {
  dati.in[i] = inn[i];
  dati.out[i] = ou[i];
}

Similarly, in your thread, you're only processing the first element in the array. So this code:

Args* arg = (Args*)param;
cvtColor(*arg->in,*arg->out,CV_BGR2GRAY);

would need to become something like this:

Args* arg = (Args*)param;
for (int i = 0; i < 6; i++) {
  cvtColor(arg->in[i],arg->out[0],CV_BGR2GRAY);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM