您可以使用
conditional variable使线程进入睡眠状态,直到发出信号.
volatile int jobs[MAX_THREADS]; // global job indicator array
pthread_cond_t th_cond; // threads wait on this
pthread_mutex_t th_mutex; // mutex to protect the signal
int busyThreads = MAX_THREADS;
pthread_cond_t m_cond; // main thread waits on this
pthread_mutex_t m_mutex; // mutex to protect main signal
thread_execute(void *args)
{
tid = get_id(args);
while(jobs[tid] != -1)
{
if(jobs[tid] == 0) continue; // no job
if(jobs[tid] == JOBS_1)
{
jobs1();
jobs[tid] = 0; // go back to idle state
pthread_mutex_lock(&th_mutex);
pthread_mutex_lock(&m_mutex);
--busyThreads; // one less worker
pthread_cond_signal(&m_cond); // signal main to check progress
pthread_mutex_unlock(&m_mutex);
pthread_cond_wait(&th_cond, &th_mutex); // wait for next job
pthread_mutex_unlock(&th_mutex);
}
if(jobs[tid] == JOBS_2)
{
jobs2();
jobs[tid] = 0; // go back to idle state
pthread_mutex_lock(&th_mutex);
--busyThreads;
pthread_cond_wait(&th_cond, &th_mutex);
pthread_mutex_unlock(&th_mutex);
}
}
pthread_exit(NULL);
}
然后在主要:
int main()
{
sem_init(&semaphore, 0, 0);
jobs[0...MAX_THREADS] = 0;
spawn_threads();
// Dispatch first job
jobs[0...MAX_THREADS] = JOBS_1;
int semvalue = 0;
pthread_mutex_lock(&m_mutex);
while(busyThreads > 0) // check number of active workers
pthread_cond_wait(&m_cond, &m_mutex);
pthread_mutex_unlock(&m_mutex);
busyThreads = MAX_THREADS;
pthread_mutex_lock(&th_mutex);
pthread_cond_broadcast(&th_cond); // signal all workers to resume
pthread_mutex_unlock(&th_mutex);
// same for JOBS_2;
jobs[0...MAX_THREADS] = -1; // No more jobs
pthread_join();
}