线程等待与唤醒c语言,c – 在pthreads中唤醒单个线程而不是忙等待

您可以使用

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();

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值