#include "resources.h" #include #include void *t1(void *_); void *t2(void *_); void *t3(void *_); void msg(int tid, const char *str); enum { TABLE, CHAIR, LAMP, SPOON, CROW = 99, }; int main() { resources_init(); resources_create(TABLE, 2); resources_create(LAMP, 2); resources_create(CROW, 1); resources_create(CHAIR, 6); pthread_t i1, i2, i3; pthread_create(&i1, NULL, t1, NULL); pthread_create(&i2, NULL, t2, NULL); pthread_create(&i3, NULL, t3, NULL); struct resources_request res0[] = {{CHAIR, 2}}; msg(0, "requests 2 chairs"); resources_take(1, res0); msg(0, "got its chairs"); usleep(100000); msg(0, "spawning spoons"); resources_create(SPOON, 8); msg(0, "returns chairs"); resources_return(CHAIR, 2); struct resources_request res2[] = {{LAMP, 1}, {SPOON, 4}}; msg(0, "requests a lamp and 4 spoons"); resources_take(2, res2); msg(0, "got a lamp and 4 spoons"); usleep(300000); msg(0, "returns a lamp and 4 spoons"); resources_return(LAMP, 1); resources_return(SPOON, 4); pthread_join(i1, NULL); pthread_join(i2, NULL); pthread_join(i3, NULL); return 0; } void *t1(void *_) { struct resources_request res1[] = {{TABLE, 1}, {LAMP, 2}, {CROW, 1}}; msg(1, "requests a table, two lamps and a crow"); resources_take(3, res1); msg(1, "got what it wanted"); usleep(200000); msg(1, "returns crow and one lamp"); resources_return(CROW, 1); resources_return(LAMP, 1); usleep(200000); msg(1, "returns the other lamp and a table"); resources_return(LAMP, 1); resources_return(TABLE, 1); return NULL; } void *t2(void *_) { usleep(200000); struct resources_request res3[] = {{CHAIR, 2}, {LAMP, 1}}; msg(2, "requests 2 chairs and a lamp"); resources_take(2, res3); msg(2, "got what it wanted"); usleep(100000); msg(2, "returns all it had"); resources_return(CHAIR, 2); resources_return(LAMP, 1); return NULL; } void *t3(void *_) { usleep(300000); struct resources_request res4[] = {{CHAIR, 1}}; msg(3, "requests a single chair"); resources_take(1, res4); msg(3, "got a chair"); usleep(100000); msg(3, "returns a chair"); resources_return(CHAIR, 1); return NULL; } #include #include void msg(int tid, const char *str) { struct timespec tp; clock_gettime(CLOCK_REALTIME, &tp); static struct timespec worldstart = {0, 0}; static int colors[] = {0, 32, 33, 36}; if (worldstart.tv_sec == 0) worldstart = tp; tp.tv_sec -= worldstart.tv_sec; tp.tv_nsec -= worldstart.tv_nsec; if (tp.tv_nsec < 0) { tp.tv_nsec += 1e9; tp.tv_sec--; } printf("\e[%dm%2ld.%03ld|t%d %s\e[0m\n", colors[tid], tp.tv_sec, tp.tv_nsec / (int)1e6, tid, str); }