2024-11-20 17:55:57 +02:00
|
|
|
#include <pthread.h>
|
2024-11-20 15:39:10 +02:00
|
|
|
#include <unistd.h>
|
|
|
|
#include <assert.h>
|
|
|
|
#include <stdio.h>
|
|
|
|
|
2024-11-26 22:59:23 +02:00
|
|
|
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
|
|
|
|
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
|
|
|
|
|
2024-11-20 17:55:57 +02:00
|
|
|
static void *thread(void *arg) {
|
2024-11-26 22:59:23 +02:00
|
|
|
const char *name = (const char *) arg;
|
|
|
|
printf("[%s] wait\n", name);
|
|
|
|
pthread_mutex_lock(&mutex);
|
|
|
|
pthread_cond_wait(&cond, &mutex);
|
|
|
|
pthread_mutex_unlock(&mutex);
|
|
|
|
printf("[%s] done\n", name);
|
|
|
|
return NULL;
|
2024-11-20 17:55:57 +02:00
|
|
|
}
|
2024-11-20 15:39:10 +02:00
|
|
|
|
2024-11-15 23:18:04 +02:00
|
|
|
int main(int argc, const char **argv) {
|
2024-11-26 22:59:23 +02:00
|
|
|
pthread_t handle0, handle1;
|
|
|
|
pthread_create(&handle0, NULL, thread, "thread0");
|
|
|
|
pthread_create(&handle1, NULL, thread, "thread1");
|
2024-11-20 17:55:57 +02:00
|
|
|
|
2024-11-26 22:59:23 +02:00
|
|
|
sleep(3);
|
2024-11-20 15:39:10 +02:00
|
|
|
|
2024-11-26 22:59:23 +02:00
|
|
|
pthread_mutex_lock(&mutex);
|
|
|
|
pthread_cond_broadcast(&cond);
|
|
|
|
pthread_mutex_unlock(&mutex);
|
2024-11-20 15:39:10 +02:00
|
|
|
|
2024-11-26 22:59:23 +02:00
|
|
|
pthread_join(handle0, NULL);
|
|
|
|
pthread_join(handle1, NULL);
|
|
|
|
printf("[main] finished\n");
|
2024-11-20 15:39:10 +02:00
|
|
|
|
2024-11-11 15:19:36 +02:00
|
|
|
return 0;
|
|
|
|
}
|