Hello friends. I'm just wondering what the correct way to parse a structure object in a looped CreateThread would be. I'll explain what I mean.
Basically, I have a structure object, and I want each newly created thread to have a copy of this structure object. The way I'm doing it at the moment is like so (parsing a pointer to the structure and converting it to a struct object from a pointer to void):
Code:
my_struct x;
for (unsigned int i = 0; i < scan_args.threads; i++) {
x.thread_id = i;
CreateThread(0, 0, (LPTHREAD_START_ROUTINE)&Initialize_Thread, &x, 0, 0);
}
Initialize_Thread(void * x) {
my_struct myStructure = *(my_struct *)x;
// myStructure is now a copy of the original structure
}
The problem with this, it's causing a race condition because the for loop is executing faster than each thread is copying structures. Therefore, the copied structures member (thread_id) is usually wrong. This is because at the point at which the thread copies the structure the original structures thread_id has already changed multiple times (aka the for loop is steps ahead of the thread).
So, how exactly can I copy the structure inside the for loop instead of parsing a pointer, and instead just parse the copy.
If I was to do it like this:
Code:
for (unsigned int i = 0; i < scan_args.threads; i++) {
x.thread_id = i;
my_struct copy = x;
CreateThread(0, 0, (LPTHREAD_START_ROUTINE)&Initialize_Thread, ©, 0, 0);
}
Wouldn't this cause race conditions as well? Because... Is the memory free'd or overwritten or manipulated each time through the for loop, or once the scope of the loop has been broken?
I hope my explanation wasn't too confusing... Thanks!