00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021 #include "defs.h"
00022 #include <pthread.h>
00023
00024 #define MAX_ENTRIES 100
00025
00026 struct dict {
00027 int d_nentries;
00028 char *d_entry[MAX_ENTRIES];
00029 bool d_issorted;
00030 };
00031
00032 static int compar(const void *x, const void *y)
00033 {
00034 return strcmp(*(char **)x, *(char **)y);
00035 }
00036
00037 static void *sorter(void *arg)
00038 {
00039 struct dict *d = arg;
00040
00041 while (true) {
00042 if (!d->d_issorted) {
00043 qsort(d->d_entry, d->d_nentries, sizeof(char *), compar);
00044 d->d_issorted = true;
00045 }
00046 sleep(1);
00047 }
00048 }
00049
00050 int main(void)
00051 {
00052 struct dict dictionary;
00053 pthread_t tid;
00054 char word[100];
00055 int i;
00056 size_t wordlen;
00057
00058 dictionary.d_nentries = 0;
00059 dictionary.d_issorted = true;
00060 ec_rv( pthread_create(&tid, NULL, sorter, &dictionary) )
00061 while (!feof(stdin)) {
00062 printf("Word? ");
00063 if (fgets(word, sizeof(word), stdin) == NULL && ferror(stdin))
00064 EC_FAIL
00065 if (word[0] == '-') {
00066 if (dictionary.d_issorted)
00067 for (i = 0; i < dictionary.d_nentries; i++)
00068 printf("\t%s\n", dictionary.d_entry[i]);
00069 else
00070 printf("Not sorted -- try again later\n");
00071 continue;
00072 }
00073 wordlen = strlen(word);
00074 if (word[wordlen - 1] == '\n')
00075 word[--wordlen] = '\0';
00076 if (dictionary.d_nentries >= MAX_ENTRIES) {
00077 errno = E2BIG;
00078 EC_FAIL
00079 }
00080 ec_null( dictionary.d_entry[dictionary.d_nentries] =
00081 malloc(wordlen + 1) )
00082 strcpy(dictionary.d_entry[dictionary.d_nentries], word);
00083
00084
00085
00086
00087 dictionary.d_nentries++;
00088
00089
00090
00091
00092
00093 dictionary.d_issorted = false;
00094 }
00095 return EXIT_SUCCESS;
00096
00097 EC_CLEANUP_BGN
00098 return EXIT_FAILURE;
00099 EC_CLEANUP_END
00100 }