相关疑难解决方法(0)

何时使用pthread条件变量?

pthread问题;

看来条件变量只有在另一个线程调用pthread_cond_notify之前调用pthread_cond_wait时才有效.如果在等待之前以某种方式通知,则等待将被卡住;

我的问题是; 什么时候应该使用条件变量?调度程序可以抢占线程并在等待之前通知发生;

等待信号量没有这个问题 - 这些有一个计数器,还是什么时候条件变量更好?

这是一个测试

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

// test of conditional variables;
// if cond-var is notified before wait starts, then wait never wakes up !!!
// better to use semaphores than this crap.

pthread_mutex_t cond_var_lock =  PTHREAD_MUTEX_INITIALIZER; 
pthread_cond_t cond_var = PTHREAD_COND_INITIALIZER;

int wait_first = 1;

void *tfunc(void *arg)
{
    (void) arg;

    if (!wait_first)
        sleep(1);

    fprintf(stderr,"on enter cond_var_lock %lx\n", pthread_self());
    pthread_mutex_lock( &cond_var_lock);
    fprintf(stderr,"before pthread_cond_wait %lx\n", pthread_self());
    pthread_cond_wait( &cond_var, &cond_var_lock);
    fprintf(stderr,"after pthread_cond_wait %lx\n", pthread_self()); …
Run Code Online (Sandbox Code Playgroud)

c linux pthreads

18
推荐指数
1
解决办法
4万
查看次数

标签 统计

c ×1

linux ×1

pthreads ×1