Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <pthread.h>
- #include <time.h>
- #include "errors.h"
- typedef struct alarm_tag {
- struct alarm_tag *link;
- int seconds;
- time_t time; /* seconds from EPOCH */
- char message[128];
- int id;
- int dsp_id;
- } alarm_t;
- pthread_mutex_t alarm_mutex = PTHREAD_MUTEX_INITIALIZER;
- alarm_t *alarm_list = NULL;
- int main (int argc, char *argv[])
- {
- int status;
- char line[128];
- alarm_t *alarm, **last, *next;
- pthread_t thread;
- status = pthread_create (
- &thread, NULL, alarm_thread, NULL);
- if (status != 0)
- err_abort (status, "Create alarm thread");
- while (1) {
- printf ("alarm> ");
- if (fgets (line, sizeof (line), stdin) == NULL) exit (0);
- if (strlen (line) <= 1) continue;
- alarm = (alarm_t*)malloc (sizeof (alarm_t));
- if (alarm == NULL)
- errno_abort ("Allocate alarm");
- if (sscanf (line, "Start_Alarm(%d) %d %128[^\n]",
- &alarm->id, &alarm->seconds, alarm->message)) {
- status = pthread_mutex_lock (&alarm_mutex);
- if (status != 0)
- err_abort (status, "Lock mutex");
- printf ("Alarm(%d) Inserted by Main Thread %ld Into Alarm List at\
- %ld: %d %s\n", alarm->id, pthread_self(), time(NULL),
- alarm->seconds, alarm->message);
- alarm->time = time (NULL) + alarm->seconds;
- /*
- * Insert the new alarm into the list of alarms, sorted by
- * order of their id (increasing order).
- */
- last = &alarm_list;
- next = *last;
- while (next != NULL) {
- if (next->id <= alarm->id) {
- alarm->link = next;
- *last = alarm;
- break;
- }
- last = &next->link;
- next = next->link;
- }
- if (next == NULL) {
- *last = alarm;
- alarm->link = NULL;
- }
- status = pthread_mutex_unlock (&alarm_mutex);
- if (status != 0)
- err_abort (status, "Unlock mutex");
- }
- else if (sscanf (line, "Change_Alarm(%d) %d %128[^\n]",
- &alarm->id, &alarm->seconds, alarm->message)) {
- status = pthread_mutex_lock (&alarm_mutex);
- if (status != 0)
- err_abort (status, "Lock mutex");
- // Do Something
- status = pthread_mutex_unlock (&alarm_mutex);
- if (status != 0)
- err_abort (status, "Unlock mutex");
- }
- else {
- fprintf (stderr, "Bad command\n");
- free (alarm);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement