vector<int> global_vector;
int Thread(void*){
cin.get();
global_vector.push_back(15);//lets say, that vector will be reallocated now
return 0;
}
int main(){
//CreateThread
vector<int>::iterator i;
while(true){
for(i = global_vector.begin(); i != global_vector.end(); i++){
cout<<*i;//The app will crash here because
//global_vector gets reallocated and i doesn't
//point where it should any more
}
}
return 0;
}
What could I do with this? The only thing that comes to head is some sort of messaging system, though that seems a needlessly complex solution for a simple problem...
Though I can't find LockMutex on msdn? (only CreateMutex) In what library is it?
I don't know if it is an actual function. I just made it up (pseudocode).
There's definitely a way to lock mutexes though, it depends on whatever lib you're using. The CreateMutex documentation should have a link to related functions in the "See Also" section.
Also, doesn't using mutexes solve the whole problem?
Yeah. x_x I don't know why I did that the hard way, but yeah you're right. Heh.
Though I can't find LockMutex on msdn? (only CreateMutex) What library is it in?
It should look like this:
1 2 3 4 5 6 7 8 9
HANDLE mutex = CreateMutex(0,false,0); // initialize once.
// use this around every critical section
WaitForSingleObject(mutex, INFINITE);
...
ReleaseMutex(mutex);
CloseHandle(muteX); // the typical free stuff...
Don't give the mutex a name or else it will be a system-wide inter-process lock.
Instead of the Windows-Functions, you can have a look at boost::thread, which provides mutexes too and will be the API that will come with the standard library some day, so you already preparing ;-)