123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133 |
- #include <pthread.h>
- #include <stdio.h>
- #include <unistd.h>
- #include <malloc.h>
- struct Time
- {
- unsigned int hour;
- unsigned int minute;
- unsigned int second;
- };
- typedef struct Time Time;
- struct Worker
- {
- int id;
- Time time;
- };
- typedef struct Worker Worker;
- static void* showTime(void* arg);
- static void* workClock(void* arg);
- void PassTime(Time* time);
- pthread_t pt_watcher;
- pthread_t pt_clock;
- pthread_t pt_timer;
- pthread_t pt_stopwatch;
- int startThread(pthread_t* thread, void*(func)(void*), Worker* worker)
- {
- puts("Я стартанул часы.");
- int status = pthread_create(thread, NULL, func, worker);
- if(status != 0)
- {
- printf("Ошибка, статус = %d", status);
- return(-1);
- }
- return status;
- }
- int main()
- {
- int identifiers[] = { 1, 2, 3 };
- Time* clock = calloc(1, sizeof(Time));
- Time* timer = calloc(1, sizeof(Time));
- Time* stopwatch = calloc(1, sizeof(Time));
- Worker* worker = calloc(1, sizeof(Worker));
- worker->id = identifiers[0];
- //startThread(&pt_clock, workClock, worker);
- sleep(1);
- puts("Я поспал.");
- pthread_create(&pt_clock, NULL, workClock, worker);
- pthread_create(&pt_watcher, NULL, showTime, &(worker->time));
- void* res;
- pthread_join(pt_clock, &res);
- puts((char*)res);
- pthread_join(pt_watcher, &res);
- puts((char*)res);
-
- puts("Я все.");
- return 0;
- }
- void PassTime(Time* time)
- {
- puts("Вот счетчик.");
- while (1)
- {
- sleep(1);
- time->second++;
- if (time->second == 60)
- {
- time->second = 0;
- time->minute++;
- }
- if (time->minute == 60)
- {
- time->minute = 0;
- time->hour++;
- }
- if (time->hour == 24)
- {
- time->hour = 0;
- }
- }
- }
- static void* showTime(void* arg)
- {
- Time* time = (Time*) arg;
- Time* changeTime = malloc(sizeof(Time));
- changeTime->hour = time->hour;
- changeTime->minute = time->minute;
- changeTime->second = time->second;
- char* stringTime = malloc(sizeof(char) * 9);
- sprintf(stringTime, "%02d:%02d:%02d\0", time->hour, time->minute, time->second);
- puts(stringTime);
- for (;;)
- {
- if (changeTime->hour != time->hour || changeTime->minute != time->minute || changeTime->second != time->second)
- {
- sprintf(stringTime, "%02d:%02d:%02d\0", time->hour, time->minute, time->second);
- puts(stringTime);
- changeTime->hour = time->hour;
- changeTime->minute = time->minute;
- changeTime->second = time->second;
- }
- }
- pthread_exit(0);
- }
- static void* workClock(void* arg)
- {
- puts("Вот часы.");
- Worker* worker = (Worker*) arg;
- PassTime(&(worker->time));
- pthread_exit(0);
- }
|