2 * SPDX-License-Identifier: BSD-2-Clause
4 * Copyright (C) 2009 Gabor Kovesdan <gabor@FreeBSD.org>
5 * Copyright (C) 2012 Oleg Moskalenko <mom040267@gmail.com>
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
35 #include <sys/types.h>
36 #include <sys/queue.h>
40 #if defined(SORT_THREADS)
43 #include <semaphore.h>
53 #include "radixsort.h"
55 unsigned long long free_memory = 1000000;
56 unsigned long long available_free_memory = 1000000;
60 const char *tmpdir = "/var/tmp";
61 const char *compress_program;
63 size_t max_open_files = 16;
66 * File reader structure
73 unsigned char *mmapaddr;
74 unsigned char *mmapptr;
82 * Structure to be used in file merge process.
86 struct file_reader *fr;
87 struct sort_list_item *si; /* current top line */
92 * List elements of "cleanable" files list.
97 LIST_ENTRY(CLEANABLE_FILE) files;
101 * List header of "cleanable" files list.
103 static LIST_HEAD(CLEANABLE_FILES,CLEANABLE_FILE) tmp_files;
106 * Semaphore to protect the tmp file list.
107 * We use semaphore here because it is signal-safe, according to POSIX.
108 * And semaphore does not require pthread library.
110 static sem_t tmp_files_sem;
112 static void mt_sort(struct sort_list *list,
113 int (*sort_func)(void *, size_t, size_t,
114 int (*)(const void *, const void *)), const char* fn);
117 * Init tmp files list
123 LIST_INIT(&tmp_files);
124 sem_init(&tmp_files_sem, 0, 1);
128 * Save name of a tmp file for signal cleanup
131 tmp_file_atexit(const char *tmp_file)
135 sem_wait(&tmp_files_sem);
136 struct CLEANABLE_FILE *item =
137 sort_malloc(sizeof(struct CLEANABLE_FILE));
138 item->fn = sort_strdup(tmp_file);
139 LIST_INSERT_HEAD(&tmp_files, item, files);
140 sem_post(&tmp_files_sem);
148 clear_tmp_files(void)
150 struct CLEANABLE_FILE *item;
152 sem_wait(&tmp_files_sem);
153 LIST_FOREACH(item,&tmp_files,files) {
154 if ((item) && (item->fn))
157 sem_post(&tmp_files_sem);
161 * Check whether a file is a temporary file
164 file_is_tmp(const char* fn)
166 struct CLEANABLE_FILE *item;
170 sem_wait(&tmp_files_sem);
171 LIST_FOREACH(item,&tmp_files,files) {
172 if ((item) && (item->fn))
173 if (strcmp(item->fn, fn) == 0) {
178 sem_post(&tmp_files_sem);
185 * Generate new temporary file name
188 new_tmp_file_name(void)
193 if (asprintf(&ret, "%s/.bsdsort.XXXXXXXXXX", tmpdir) == -1)
194 err(2, "asprintf()");
195 if ((fd = mkstemp(ret)) == -1)
199 tmp_file_atexit(ret);
204 * Initialize file list
207 file_list_init(struct file_list *fl, bool tmp)
211 memset(fl, 0, sizeof(*fl));
217 * Add a file name to the list
220 file_list_add(struct file_list *fl, const char *fn, bool allocate)
224 if (fl->count >= fl->sz || (fl->fns == NULL)) {
225 fl->sz = (fl->sz) * 2 + 1;
226 fl->fns = sort_realloc(fl->fns, fl->sz *
229 fl->fns[fl->count] = allocate ? sort_strdup(fn) : fn;
235 * Populate file list from array of file names
238 file_list_populate(struct file_list *fl, int argc, char **argv, bool allocate)
244 for (i = 0; i < argc; i++)
245 file_list_add(fl, argv[i], allocate);
250 * Clean file list data and delete the files,
251 * if this is a list of temporary files
254 file_list_clean(struct file_list *fl)
261 for (i = 0; i < fl->count; i++) {
265 sort_free(fl->fns[i]);
282 sort_list_init(struct sort_list *l)
286 memset(l, 0, sizeof(*l));
287 l->memsize = sizeof(struct sort_list);
292 * Add string to sort list
295 sort_list_add(struct sort_list *l, struct bwstring *str)
299 size_t indx = l->count;
301 if ((l->list == NULL) || (indx >= l->size)) {
302 size_t newsize = (l->size + 1) + 1024;
304 l->list = sort_realloc(l->list,
305 sizeof(struct sort_list_item*) * newsize);
306 l->memsize += (newsize - l->size) *
307 sizeof(struct sort_list_item*);
310 l->list[indx] = sort_list_item_alloc();
311 sort_list_item_set(l->list[indx], str);
312 l->memsize += sort_list_item_size(l->list[indx]);
318 * Clean sort list data
321 sort_list_clean(struct sort_list *l)
328 for (i = 0; i < l->count; i++) {
329 struct sort_list_item *item;
334 sort_list_item_clean(item);
344 l->memsize = sizeof(struct sort_list);
349 * Write sort list to file
352 sort_list_dump(struct sort_list *l, const char *fn)
358 f = openfile(fn, "w");
364 if (!(sort_opts_vals.uflag)) {
365 for (i = 0; i < l->count; ++i)
366 bwsfwrite(l->list[i]->str, f,
367 sort_opts_vals.zflag);
369 struct sort_list_item *last_printed_item = NULL;
370 struct sort_list_item *item;
371 for (i = 0; i < l->count; ++i) {
373 if ((last_printed_item == NULL) ||
374 list_coll(&last_printed_item, &item)) {
375 bwsfwrite(item->str, f, sort_opts_vals.zflag);
376 last_printed_item = item;
387 * Checks if the given file is sorted. Stops at the first disorder,
388 * prints the disordered line and returns 1.
391 check(const char *fn)
393 struct bwstring *s1, *s2, *s1disorder, *s2disorder;
394 struct file_reader *fr;
395 struct keys_array *ka1, *ka2;
397 size_t pos, posdisorder;
399 s1 = s2 = s1disorder = s2disorder = NULL;
402 fr = file_reader_init(fn);
413 s1 = file_reader_readline(fr);
417 ka1 = keys_array_alloc();
420 s2 = file_reader_readline(fr);
424 ka2 = keys_array_alloc();
430 bwsprintf(stdout, s2, "s1=<", ">");
431 bwsprintf(stdout, s1, "s2=<", ">");
433 int cmp = key_coll(ka2, ka1, 0);
435 printf("; cmp1=%d", cmp);
437 if (!cmp && sort_opts_vals.complex_sort &&
438 !(sort_opts_vals.uflag) && !(sort_opts_vals.sflag)) {
439 cmp = top_level_str_coll(s2, s1);
441 printf("; cmp2=%d", cmp);
446 if ((sort_opts_vals.uflag && (cmp <= 0)) || (cmp < 0)) {
447 if (!(sort_opts_vals.csilentflag)) {
448 s2disorder = bwsdup(s2);
451 s1disorder = bwsdup(s1);
459 clean_keys_array(s1, ka1);
467 s2 = file_reader_readline(fr);
471 ka2 = keys_array_alloc();
477 clean_keys_array(s1, ka1);
485 clean_keys_array(s2, ka2);
492 if ((fn == NULL) || (*fn == 0) || (strcmp(fn, "-") == 0)) {
494 s2 = file_reader_readline(fr);
501 file_reader_free(fr);
504 bws_disorder_warnx(s2disorder, fn, posdisorder);
506 bws_disorder_warnx(s1disorder, fn, posdisorder);
507 if (s1disorder != s2disorder)
522 * Opens a file. If the given filename is "-", stdout will be
526 openfile(const char *fn, const char *mode)
530 if (strcmp(fn, "-") == 0)
531 return ((mode && mode[0] == 'r') ? stdin : stdout);
533 mode_t orig_file_mask = 0;
534 int is_tmp = file_is_tmp(fn);
536 if (is_tmp && (mode[0] == 'w'))
537 orig_file_mask = umask(S_IWGRP | S_IWOTH |
540 if (is_tmp && (compress_program != NULL)) {
547 r = asprintf(&cmd, "cat %s | %s -d",
548 fn, compress_program);
549 else if (mode[0] == 'w')
550 r = asprintf(&cmd, "%s > %s",
551 compress_program, fn);
553 err(2, "%s", getstr(7));
556 err(2, "aspritnf()");
558 if ((file = popen(cmd, mode)) == NULL)
562 if ((file = fopen(fn, mode)) == NULL)
565 if (is_tmp && (mode[0] == 'w'))
566 umask(orig_file_mask);
575 closefile(FILE *f, const char *fn)
577 if (f == NULL || f == stdin)
583 if (file_is_tmp(fn) && compress_program != NULL) {
591 * Reads a file into the internal buffer.
594 file_reader_init(const char *fsrc)
596 struct file_reader *ret;
601 ret = sort_calloc(1, sizeof(struct file_reader));
603 ret->elsymb = sort_opts_vals.zflag ? '\0' : '\n';
604 ret->fname = sort_strdup(fsrc);
606 if (strcmp(fsrc, "-") && (compress_program == NULL) && use_mmap) {
609 struct stat stat_buf;
614 flags = MAP_NOCORE | MAP_NOSYNC;
616 fd = open(fsrc, O_RDONLY);
620 if (fstat(fd, &stat_buf) < 0) {
625 sz = stat_buf.st_size;
627 #if defined(MAP_PREFAULT_READ)
628 flags |= MAP_PREFAULT_READ;
631 addr = mmap(NULL, sz, PROT_READ, flags, fd, 0);
632 if (addr == MAP_FAILED) {
638 ret->mmapaddr = addr;
640 ret->mmapptr = ret->mmapaddr;
645 if (ret->mmapaddr == NULL) {
646 ret->file = openfile(fsrc, "r");
647 if (ret->file == NULL)
655 file_reader_readline(struct file_reader *fr)
657 struct bwstring *ret = NULL;
660 unsigned char *mmapend;
662 mmapend = fr->mmapaddr + fr->mmapsize;
663 if (fr->mmapptr >= mmapend)
666 unsigned char *strend;
669 sz = mmapend - fr->mmapptr;
670 strend = memchr(fr->mmapptr, fr->elsymb, sz);
672 if (strend == NULL) {
673 ret = bwscsbdup(fr->mmapptr, sz);
674 fr->mmapptr = mmapend;
676 ret = bwscsbdup(fr->mmapptr, strend -
678 fr->mmapptr = strend + 1;
684 len = getdelim(&fr->buffer, &fr->bsz, fr->elsymb, fr->file);
690 if (len > 0 && fr->buffer[len - 1] == fr->elsymb)
692 ret = bwscsbdup(fr->buffer, len);
699 file_reader_clean(struct file_reader *fr)
706 munmap(fr->mmapaddr, fr->mmapsize);
711 closefile(fr->file, fr->fname);
713 memset(fr, 0, sizeof(struct file_reader));
717 file_reader_free(struct file_reader *fr)
722 file_reader_clean(fr);
727 procfile(const char *fsrc, struct sort_list *list, struct file_list *fl)
729 struct file_reader *fr;
731 fr = file_reader_init(fsrc);
735 /* file browse cycle */
737 struct bwstring *bws;
739 bws = file_reader_readline(fr);
744 sort_list_add(list, bws);
746 if (list->memsize >= available_free_memory) {
749 fn = new_tmp_file_name();
750 sort_list_to_file(list, fn);
751 file_list_add(fl, fn, false);
752 sort_list_clean(list);
756 file_reader_free(fr);
762 * Compare file headers. Files with EOF always go to the end of the list.
765 file_header_cmp(struct file_header *f1, struct file_header *f2)
771 if (f1->fr == NULL) {
772 return ((f2->fr == NULL) ? 0 : +1);
773 } else if (f2->fr == NULL)
778 ret = list_coll(&(f1->si), &(f2->si));
780 return ((f1->file_pos < f2->file_pos) ? -1 : +1);
787 * Allocate and init file header structure
790 file_header_init(struct file_header **fh, const char *fn, size_t file_pos)
794 struct bwstring *line;
796 *fh = sort_malloc(sizeof(struct file_header));
797 (*fh)->file_pos = file_pos;
798 (*fh)->fr = file_reader_init(fn);
799 if ((*fh)->fr == NULL) {
801 err(2, "%s", getstr(8));
803 line = file_reader_readline((*fh)->fr);
805 file_reader_free((*fh)->fr);
809 (*fh)->si = sort_list_item_alloc();
810 sort_list_item_set((*fh)->si, line);
819 file_header_close(struct file_header **fh)
823 file_reader_free((*fh)->fr);
826 sort_list_item_clean((*fh)->si);
827 sort_free((*fh)->si);
836 * Swap two array elements
839 file_header_swap(struct file_header **fh, size_t i1, size_t i2)
841 struct file_header *tmp;
848 /* heap algorithm ==>> */
851 * See heap sort algorithm
852 * "Raises" last element to its right place
855 file_header_heap_swim(struct file_header **fh, size_t indx)
861 parent_index = (indx - 1) >> 1;
863 if (file_header_cmp(fh[indx], fh[parent_index]) < 0) {
864 /* swap child and parent and continue */
865 file_header_swap(fh, indx, parent_index);
866 file_header_heap_swim(fh, parent_index);
872 * Sink the top element to its correct position
875 file_header_heap_sink(struct file_header **fh, size_t indx, size_t size)
877 size_t left_child_index;
878 size_t right_child_index;
880 left_child_index = indx + indx + 1;
881 right_child_index = left_child_index + 1;
883 if (left_child_index < size) {
884 size_t min_child_index;
886 min_child_index = left_child_index;
888 if ((right_child_index < size) &&
889 (file_header_cmp(fh[left_child_index],
890 fh[right_child_index]) > 0))
891 min_child_index = right_child_index;
892 if (file_header_cmp(fh[indx], fh[min_child_index]) > 0) {
893 file_header_swap(fh, indx, min_child_index);
894 file_header_heap_sink(fh, min_child_index, size);
899 /* <<== heap algorithm */
902 * Adds element to the "left" end
905 file_header_list_rearrange_from_header(struct file_header **fh, size_t size)
908 file_header_heap_sink(fh, 0, size);
912 * Adds element to the "right" end
915 file_header_list_push(struct file_header *f, struct file_header **fh, size_t size)
919 file_header_heap_swim(fh, size - 1);
924 struct bwstring *str;
928 * Prints the current line of the file
931 file_header_print(struct file_header *fh, FILE *f_out, struct last_printed *lp)
934 if (fh && fh->fr && f_out && fh->si && fh->si->str) {
935 if (sort_opts_vals.uflag) {
936 if ((lp->str == NULL) || (str_list_coll(lp->str, &(fh->si)))) {
937 bwsfwrite(fh->si->str, f_out, sort_opts_vals.zflag);
940 lp->str = bwsdup(fh->si->str);
943 bwsfwrite(fh->si->str, f_out, sort_opts_vals.zflag);
951 file_header_read_next(struct file_header *fh)
955 struct bwstring *tmp;
957 tmp = file_reader_readline(fh->fr);
959 file_reader_free(fh->fr);
962 sort_list_item_clean(fh->si);
968 fh->si = sort_list_item_alloc();
969 sort_list_item_set(fh->si, tmp);
975 * Merge array of "files headers"
978 file_headers_merge(size_t fnum, struct file_header **fh, FILE *f_out)
980 struct last_printed lp;
983 memset(&lp, 0, sizeof(lp));
986 * construct the initial sort structure
988 for (i = 0; i < fnum; i++)
989 file_header_list_push(fh[i], fh, i);
991 while (fh[0]->fr) { /* unfinished files are always in front */
992 /* output the smallest line: */
993 file_header_print(fh[0], f_out, &lp);
994 /* read a new line, if possible: */
995 file_header_read_next(fh[0]);
996 /* re-arrange the list: */
997 file_header_list_rearrange_from_header(fh, fnum);
1005 * Merges the given files into the output file, which can be
1009 merge_files_array(size_t argc, const char **argv, const char *fn_out)
1012 if (argv && fn_out) {
1013 struct file_header **fh;
1017 f_out = openfile(fn_out, "w");
1022 fh = sort_malloc((argc + 1) * sizeof(struct file_header *));
1024 for (i = 0; i < argc; i++)
1025 file_header_init(fh + i, argv[i], (size_t) i);
1027 file_headers_merge(argc, fh, f_out);
1029 for (i = 0; i < argc; i++)
1030 file_header_close(fh + i);
1034 closefile(f_out, fn_out);
1039 * Shrinks the file list until its size smaller than max number of opened files
1042 shrink_file_list(struct file_list *fl)
1045 if ((fl == NULL) || (size_t) (fl->count) < max_open_files)
1048 struct file_list new_fl;
1051 file_list_init(&new_fl, true);
1052 while (indx < fl->count) {
1056 num = fl->count - indx;
1057 fnew = new_tmp_file_name();
1059 if ((size_t) num >= max_open_files)
1060 num = max_open_files - 1;
1061 merge_files_array(num, fl->fns + indx, fnew);
1065 for (i = 0; i < num; i++)
1066 unlink(fl->fns[indx + i]);
1068 file_list_add(&new_fl, fnew, false);
1071 fl->tmp = false; /* already taken care of */
1072 file_list_clean(fl);
1074 fl->count = new_fl.count;
1075 fl->fns = new_fl.fns;
1077 fl->tmp = new_fl.tmp;
1084 * Merge list of files
1087 merge_files(struct file_list *fl, const char *fn_out)
1091 while (shrink_file_list(fl));
1093 merge_files_array(fl->count, fl->fns, fn_out);
1098 get_sort_method_name(int sm)
1101 if (sm == SORT_MERGESORT)
1103 else if (sort_opts_vals.sort_method == SORT_RADIXSORT)
1105 else if (sort_opts_vals.sort_method == SORT_HEAPSORT)
1114 static int sort_qsort(void *list, size_t count, size_t elem_size,
1115 int (*cmp_func)(const void *, const void *))
1118 qsort(list, count, elem_size, cmp_func);
1123 * Sort list of lines and writes it to the file
1126 sort_list_to_file(struct sort_list *list, const char *outfile)
1128 struct sort_mods *sm = &(keys[0].sm);
1130 if (!(sm->Mflag) && !(sm->Rflag) && !(sm->Vflag) &&
1131 !(sm->gflag) && !(sm->hflag) && !(sm->nflag)) {
1132 if ((sort_opts_vals.sort_method == SORT_DEFAULT) && byte_sort)
1133 sort_opts_vals.sort_method = SORT_RADIXSORT;
1135 } else if (sort_opts_vals.sort_method == SORT_RADIXSORT)
1136 err(2, "%s", getstr(9));
1139 * to handle stable sort and the unique cases in the
1140 * right order, we need stable basic algorithm
1142 if (sort_opts_vals.sflag) {
1143 switch (sort_opts_vals.sort_method){
1144 case SORT_MERGESORT:
1146 case SORT_RADIXSORT:
1149 sort_opts_vals.sort_method = SORT_MERGESORT;
1152 errx(2, "%s", getstr(10));
1156 if (sort_opts_vals.sort_method == SORT_DEFAULT)
1157 sort_opts_vals.sort_method = DEFAULT_SORT_ALGORITHM;
1160 printf("sort_method=%s\n",
1161 get_sort_method_name(sort_opts_vals.sort_method));
1163 switch (sort_opts_vals.sort_method){
1164 case SORT_RADIXSORT:
1165 rxsort(list->list, list->count);
1166 sort_list_dump(list, outfile);
1168 case SORT_MERGESORT:
1169 mt_sort(list, mergesort, outfile);
1172 mt_sort(list, heapsort, outfile);
1175 mt_sort(list, sort_qsort, outfile);
1178 mt_sort(list, DEFAULT_SORT_FUNC, outfile);
1183 /******************* MT SORT ************************/
1185 #if defined(SORT_THREADS)
1186 /* semaphore to count threads */
1189 /* current system sort function */
1190 static int (*g_sort_func)(void *, size_t, size_t,
1191 int(*)(const void *, const void *));
1194 * Sort cycle thread (in multi-threaded mode)
1197 mt_sort_thread(void* arg)
1199 struct sort_list *list = arg;
1201 g_sort_func(list->list, list->count, sizeof(struct sort_list_item *),
1202 (int(*)(const void *, const void *)) list_coll);
1210 * Compare sub-lists. Empty sub-lists always go to the end of the list.
1213 sub_list_cmp(struct sort_list *l1, struct sort_list *l2)
1219 if (l1->count == 0) {
1220 return ((l2->count == 0) ? 0 : +1);
1221 } else if (l2->count == 0) {
1226 ret = list_coll(&(l1->list[0]), &(l2->list[0]));
1228 return ((l1->sub_list_pos < l2->sub_list_pos) ?
1236 * Swap two array elements
1239 sub_list_swap(struct sort_list **sl, size_t i1, size_t i2)
1241 struct sort_list *tmp;
1248 /* heap algorithm ==>> */
1251 * See heap sort algorithm
1252 * "Raises" last element to its right place
1255 sub_list_swim(struct sort_list **sl, size_t indx)
1259 size_t parent_index;
1261 parent_index = (indx - 1) >> 1;
1263 if (sub_list_cmp(sl[indx], sl[parent_index]) < 0) {
1264 /* swap child and parent and continue */
1265 sub_list_swap(sl, indx, parent_index);
1266 sub_list_swim(sl, parent_index);
1272 * Sink the top element to its correct position
1275 sub_list_sink(struct sort_list **sl, size_t indx, size_t size)
1277 size_t left_child_index;
1278 size_t right_child_index;
1280 left_child_index = indx + indx + 1;
1281 right_child_index = left_child_index + 1;
1283 if (left_child_index < size) {
1284 size_t min_child_index;
1286 min_child_index = left_child_index;
1288 if ((right_child_index < size) &&
1289 (sub_list_cmp(sl[left_child_index],
1290 sl[right_child_index]) > 0))
1291 min_child_index = right_child_index;
1292 if (sub_list_cmp(sl[indx], sl[min_child_index]) > 0) {
1293 sub_list_swap(sl, indx, min_child_index);
1294 sub_list_sink(sl, min_child_index, size);
1299 /* <<== heap algorithm */
1302 * Adds element to the "right" end
1305 sub_list_push(struct sort_list *s, struct sort_list **sl, size_t size)
1309 sub_list_swim(sl, size - 1);
1312 struct last_printed_item
1314 struct sort_list_item *item;
1318 * Prints the current line of the file
1321 sub_list_header_print(struct sort_list *sl, FILE *f_out,
1322 struct last_printed_item *lp)
1325 if (sl && sl->count && f_out && sl->list[0]->str) {
1326 if (sort_opts_vals.uflag) {
1327 if ((lp->item == NULL) || (list_coll(&(lp->item),
1329 bwsfwrite(sl->list[0]->str, f_out,
1330 sort_opts_vals.zflag);
1331 lp->item = sl->list[0];
1334 bwsfwrite(sl->list[0]->str, f_out,
1335 sort_opts_vals.zflag);
1343 sub_list_next(struct sort_list *sl)
1346 if (sl && sl->count) {
1353 * Merge sub-lists to a file
1356 merge_sub_lists(struct sort_list **sl, size_t n, FILE* f_out)
1358 struct last_printed_item lp;
1361 memset(&lp,0,sizeof(lp));
1363 /* construct the initial list: */
1364 for (i = 0; i < n; i++)
1365 sub_list_push(sl[i], sl, i);
1367 while (sl[0]->count) { /* unfinished lists are always in front */
1368 /* output the smallest line: */
1369 sub_list_header_print(sl[0], f_out, &lp);
1370 /* move to a new line, if possible: */
1371 sub_list_next(sl[0]);
1372 /* re-arrange the list: */
1373 sub_list_sink(sl, 0, n);
1378 * Merge sub-lists to a file
1381 merge_list_parts(struct sort_list **parts, size_t n, const char *fn)
1385 f_out = openfile(fn,"w");
1387 merge_sub_lists(parts, n, f_out);
1389 closefile(f_out, fn);
1392 #endif /* defined(SORT_THREADS) */
1394 * Multi-threaded sort algorithm "driver"
1397 mt_sort(struct sort_list *list,
1398 int(*sort_func)(void *, size_t, size_t, int(*)(const void *, const void *)),
1401 #if defined(SORT_THREADS)
1402 if (nthreads < 2 || list->count < MT_SORT_THRESHOLD) {
1403 size_t nthreads_save = nthreads;
1406 /* if single thread or small data, do simple sort */
1407 sort_func(list->list, list->count,
1408 sizeof(struct sort_list_item *),
1409 (int(*)(const void *, const void *)) list_coll);
1410 sort_list_dump(list, fn);
1411 #if defined(SORT_THREADS)
1412 nthreads = nthreads_save;
1414 /* multi-threaded sort */
1415 struct sort_list **parts;
1416 size_t avgsize, cstart, i;
1418 /* array of sub-lists */
1419 parts = sort_malloc(sizeof(struct sort_list*) * nthreads);
1421 avgsize = list->count / nthreads;
1423 /* set global system sort function */
1424 g_sort_func = sort_func;
1427 for (i = 0; i < nthreads; ++i) {
1430 parts[i] = sort_malloc(sizeof(struct sort_list));
1431 parts[i]->list = list->list + cstart;
1432 parts[i]->memsize = 0;
1433 parts[i]->sub_list_pos = i;
1435 sz = (i == nthreads - 1) ? list->count - cstart :
1438 parts[i]->count = sz;
1440 parts[i]->size = parts[i]->count;
1445 /* init threads counting semaphore */
1446 sem_init(&mtsem, 0, 0);
1449 for (i = 0; i < nthreads; ++i) {
1451 pthread_attr_t attr;
1453 pthread_attr_init(&attr);
1454 pthread_attr_setdetachstate(&attr, PTHREAD_DETACHED);
1457 int res = pthread_create(&pth, &attr,
1458 mt_sort_thread, parts[i]);
1462 if (errno == EAGAIN) {
1469 pthread_attr_destroy(&attr);
1472 /* wait for threads completion */
1473 for (i = 0; i < nthreads; ++i) {
1476 /* destroy the semaphore - we do not need it anymore */
1477 sem_destroy(&mtsem);
1479 /* merge sorted sub-lists to the file */
1480 merge_list_parts(parts, nthreads, fn);
1482 /* free sub-lists data */
1483 for (i = 0; i < nthreads; ++i) {
1484 sort_free(parts[i]);
1488 #endif /* defined(SORT_THREADS) */