////////////////////////////////////////////////////////////////////////// // Traveling Salesman Problem with PThreads. // Note: this is a C++ program: compile it with CC (not cc) // // Starting city is assumed to be city 0. ////////////////////////////////////////////////////////////////////////// #include #include #include #include #include #include "tsp.h" Path Shortest; Queue Q; int NumCities, NumThreads; int **Dist; // Dist[i][j] = distance from i to j // This is another way to initialize these things: pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; /////////////////////////////////////////////////////////////////////////// Path::Path () { length=0; visited=1; for (int i=0; ivisited; iAddCity(i); // decide what to do with new path if (q->visited==NumCities) { // Add last hop to return to origin: q->length += Dist[q->city[NumCities-1]][0]; // update Shortest, if q is better pthread_mutex_lock(&mutex); if (q->length < Shortest.length) Shortest = *q; pthread_mutex_unlock(&mutex); delete q; } else { Q.Put(q); // Possible optimization: compute lower bound // to complete this path; discard if bad } } delete p; // p is not needed any more } } int main(int argc, char *argv[]) { if (argc!=3) { cout << "Usage: " << argv[0] << " num_cities num_threads\n"; exit(-1); } NumCities = atoi(argv[1]); assert(NumCities<=MAXCITIES); NumThreads = atoi(argv[2]); Fill_Dist(); // initialize Distance matrix Path *P = new Path; Q.Put(P); // initialize Q with one zero-length path Shortest.length = INT_MAX; // The initial Shortest path must be bad pthread_t thread; // just a dummy variable for (int i=1; i