#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));
}
}
}
pthread_cond_signal、pthread_cond_wait example
最新推荐文章于 2021-08-18 11:05:49 发布