Hello.. I am in the progress of parallelise a multi-agent model where "agents" are different instances (thousands) of a class and they have to independently perform a relatively cpu-intensive task (few seconds).
Looks the perfect situation for a reentrant code
.... it seems... 
My problem is that, even if I mutex.lock() all the should-be-concurrent code (for debugging reasons of course) my application crash, while if I use a single thread it works.
This is the code that I implemented so far:
void
Manager_farmers::landAllocation(){
// .. serial code ..
for (int i=0; i < nThreads; i++){
Manager_farmers_threads* wThread = new Manager_farmers_threads;
wThreads.push_back(wThread);
}
// parallelise the code to z workingThreads..
for (uint y=0;y<myAgents.size();y++){
bool assigned = false;
while(!assigned) {
for (uint z=0;z<wThreads.size();z++){
if (!wThreads[z]->isRunning()){
wThreads[z]->assignJob(myAgents[y], freePlot);
wThreads[z]->start();
assigned = true;
break;
}
}
}
}
// be sure that all threads are ended..
for (int z=0; z < nThreads; z++){
wThreads[z]->wait();
}
// ..continue with serial code...
for (int i=0; i < nThreads; i++){
delete wThreads[i]; // deleting the threads
}
}
void
Manager_farmers_threads::assignJob(Agent_space* agent_h, const Pixel* plot_h){
// .. this code shuld be run serialised by the main thread..
agent = agent_h;
plot = plot_h;
agent->cachedOffer = 0;
}
void
Manager_farmers_threads::run(){
// This code should be run parallelised...
localMutex.lock();
agent->cachedOffer = agent->offerRentalPrice(plot);
localMutex.unlock();
}
void
Manager_farmers::landAllocation(){
// .. serial code ..
for (int i=0; i < nThreads; i++){
Manager_farmers_threads* wThread = new Manager_farmers_threads;
wThreads.push_back(wThread);
}
// parallelise the code to z workingThreads..
for (uint y=0;y<myAgents.size();y++){
bool assigned = false;
while(!assigned) {
for (uint z=0;z<wThreads.size();z++){
if (!wThreads[z]->isRunning()){
wThreads[z]->assignJob(myAgents[y], freePlot);
wThreads[z]->start();
assigned = true;
break;
}
}
}
}
// be sure that all threads are ended..
for (int z=0; z < nThreads; z++){
wThreads[z]->wait();
}
// ..continue with serial code...
for (int i=0; i < nThreads; i++){
delete wThreads[i]; // deleting the threads
}
}
void
Manager_farmers_threads::assignJob(Agent_space* agent_h, const Pixel* plot_h){
// .. this code shuld be run serialised by the main thread..
agent = agent_h;
plot = plot_h;
agent->cachedOffer = 0;
}
void
Manager_farmers_threads::run(){
// This code should be run parallelised...
QMutex localMutex;
localMutex.lock();
agent->cachedOffer = agent->offerRentalPrice(plot);
localMutex.unlock();
}
To copy to clipboard, switch view to plain text mode
The question is.. why for hell it is crashing even if all the code is locked ? 
Bookmarks