Serenity Operating System
at master 76 lines 1.8 kB view raw
1/* 2 * Copyright (c) 2018-2020, the SerenityOS developers. 3 * 4 * SPDX-License-Identifier: BSD-2-Clause 5 */ 6 7#include <cassert> 8#include <cstring> 9#include <ctime> 10#include <errno.h> 11#include <pthread.h> 12#include <stdio.h> 13#include <stdlib.h> 14#include <unistd.h> 15 16struct worker_t { 17 char const* name; 18 int count; 19 pthread_t thread; 20 pthread_mutex_t lock; 21 pthread_cond_t cond; 22 long int wait_time; 23}; 24 25static void* run_worker(void* args) 26{ 27 struct timespec time_to_wait = { 0, 0 }; 28 worker_t* worker = (worker_t*)args; 29 worker->count = 0; 30 31 while (worker->count < 25) { 32 time_to_wait.tv_sec = time(nullptr) + worker->wait_time; 33 pthread_mutex_lock(&worker->lock); 34 int rc = pthread_cond_timedwait(&worker->cond, &worker->lock, &time_to_wait); 35 36 // Validate return code is always timed out. 37 assert(rc == -1); 38 assert(errno == ETIMEDOUT); 39 40 worker->count++; 41 printf("Increase worker[%s] count to [%d]\n", worker->name, worker->count); 42 pthread_mutex_unlock(&worker->lock); 43 } 44 45 return nullptr; 46} 47 48static void init_worker(worker_t* worker, char const* name, long int wait_time) 49{ 50 worker->name = name; 51 worker->wait_time = wait_time; 52 53 pthread_attr_t attr; 54 pthread_attr_init(&attr); 55 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); 56 57 pthread_mutex_init(&worker->lock, nullptr); 58 pthread_cond_init(&worker->cond, nullptr); 59 pthread_create(&worker->thread, &attr, &run_worker, (void*)worker); 60 61 pthread_attr_destroy(&attr); 62} 63 64int main() 65{ 66 worker_t worker_a; 67 init_worker(&worker_a, "A", 2L); 68 69 worker_t worker_b; 70 init_worker(&worker_b, "B", 4L); 71 72 pthread_join(worker_a.thread, nullptr); 73 pthread_join(worker_b.thread, nullptr); 74 75 return EXIT_SUCCESS; 76}