Pregunta

My program reads in maze from a text file, then the main program creates 3 different threads to delve into this maze and search for the exit. When a thread discovers the exit, it will post its solution path in the main thread.

In this maze, there are pitfalls, which when a thread encounters, will "die", saving the location of that pitfall to a global array of discovered pitfall points, so that the other threads would know where to avoid. After that thread dies, the main program will respawn another thread to take its place and continue traversing the maze.

A thread may or may not encounter encounter a pitfall, and using pthread_join only waits for a specific thread. How do I make the main thread to wait for each of the threads simultaneously?

¿Fue útil?

Solución

Use a condition variable which in pthreads is pthread_cond_t. Have the main thread wait on the condition variable, and right before a thread dies have it signal the condition variable. In pseudo code something like this:

main thread

//spawn first set of threads
while(!done) {
   pthread_cond_wait(&cond, &mutex);
   //spawn another thread
}

worker thread

//traverse maze
pthread_cond_broadcast(&cond);
//thread exit

Note that when using a condition variable you need to acquire and release an associated mutex. Look at the man page for pthread_cond_wait for more details.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top