pthread_cond_signal、pthread_cond_wait example

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <signal.h>
#include <pthread.h>
#include <errno.h>

/* compile with gcc -pthread pthread_cond.c */

pthread_cond_t cv = PTHREAD_COND_INITIALIZER;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

void *thread(void *v)
{
    printf("Locking and waiting. Type unlock to unlock me.\n");
    pthread_mutex_lock(&lock);
    pthread_cond_wait(&cv, &lock);
    printf("I've been unlocked.\n");
    pthread_mutex_unlock(&lock);
    return NULL;
}

int main(int argc, char const *argv[])
{
    char cmd[1024];
    pthread_t t;

    printf("Type lock to run a thread that locks and waits.\n");
    printf("Type unlock to unlock the same thread.\n");
    while (fscanf(stdin, "%s", cmd) != EOF) {
        if (strcmp(cmd, "lock") == 0) {
            pthread_create(&t, NULL, thread, NULL);
        } else if (strcmp(cmd, "unlock") == 0) {
            if (pthread_cond_signal(&cv) != 0)
                fprintf(stderr, "pthread_cond_signal:%s\n", strerror(errno));
        }
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值