My code have one thread continuosly handling objects queued by other threads. Queued objects are created using "new" in a function that will have finished when the object will be handled. I have no problem with this but deleting the object. Should I just not delete the object? Maybe change the way of passing/creating this objects?
Object* myQueue[10];
function() {
Object* myobject = new Object();
queueObject(myobject);
}
queueObject(Object* object) {
myQueue[index_x] = object;
sem_post(&开发者_JAVA技巧amp;mySemaphore);
}
//// Thread 1
function();
...
//// Thread 2
handleObjects() {
while(true) {
sem_wait(&mySemaphore);
// handle myQueue[index_x]
delete myQueue[index_x]; ---> this produces Segmentation Fault
}
}
(the treatment of index_x is not posted to abbreviate)
I'm guessing you have a race condition. What is the synchronization mechanism you're using to prevent index_x
from being modified by both threads?
Typically a worker thread should call sem_wait, modify the critical data, and then call sem_post. I can't provide 100% accurate example code without seeing how you're using index_x, but it will look something like the following:
queueObject(Object* object) {
sem_wait(&mySemaphore);
myQueue[index_x++] = object;
sem_post(&mySemaphore);
}
handleObjects() {
while(true) {
sem_wait(&mySemaphore);
// handle myQueue[index_x]
delete myQueue[--index_x]
sem_post(&mySemaphore);
}
}
Currently it looks like you have nothing to prevent index_x from being modified by both threads, this can cause index_x to do whacky things (fail to increment or decrement being the most common whacky thing). Here is a wikipedia article explaining exactly what can go wrong.
Add some checks around the delete
if ( myQueue[index] != 0 ) {
delete myQueue[index];
myQueue[index] = 0;
} else {
for diagnosis print large warning here - something is confused
}
this catches double deletion via the same index. However there are several other ways a crash could occur. Catching those would need other actions.
Consider:
- Is there any possibility of a race condition? Could two threads attempt to delete at the same index? Do you need to add any synchronization?
- Is it possible for the same object to be added to the array twice, with different indexes? In extremis I might add code to verify that the item isn't already in the array before adding it.
精彩评论