pthread_mutex_t and pthread_cond 混合使用

来源:互联网 发布:nodejs高级编程 pdf 编辑:程序博客网 时间:2024/06/18 16:17
pthread_mutex_t count_lock;
pthread_cond_t count_nonzero;
int32_t _count = 0;


void * decrement_count(void *arg)
{
    pthread_mutex_lock (&count_lock);
    printf("decrement_count get count_lock\n");
    while (_count == 0)
    {
        printf("decrement_count count == 0 \n");
        printf("decrement_count before cond_wait \n");
        pthread_cond_wait( &count_nonzero, &count_lock);
        printf("decrement_count after cond_wait \n");
    }
    _count = _count -1;
    pthread_mutex_unlock (&count_lock);
    pthread_exit(nullptr);
}


void * increment_count(void *arg)
{
    pthread_mutex_lock(&count_lock);
    printf("increment_count get count_lock\n");
    if (_count==0)
    {
        printf("increment_count before cond_signal\n");
        pthread_cond_signal(&count_nonzero);
        printf("increment_count after cond_signal\n");
    }
    _count=_count+1;
    pthread_mutex_unlock(&count_lock);
    pthread_exit(nullptr);
}


int main(void)
{
    pthread_t tid1,tid2;
    pthread_mutex_init(&count_lock,NULL);
    pthread_cond_init(&count_nonzero,NULL);
    pthread_create(&tid1,NULL,decrement_count,NULL);
    sleep(2);
    pthread_create(&tid2,NULL,increment_count,NULL);
    sleep(10);


    while(1);
    return 0;
}
0 0
原创粉丝点击