File: tutorial-07-sort_task.cc

package info (click to toggle)
workflow 0.11.10-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,744 kB
  • sloc: cpp: 33,792; ansic: 9,393; makefile: 9; sh: 6
file content (94 lines) | stat: -rw-r--r-- 1,953 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include <stdlib.h>
#include <stdio.h>
#include "workflow/WFAlgoTaskFactory.h"
#include "workflow/WFFacilities.h"

using namespace algorithm;

static WFFacilities::WaitGroup wait_group(1);

bool use_parallel_sort = false;

void callback(WFSortTask<int> *task)
{
	/* Sort task's input and output are identical. */
	SortInput<int> *input = task->get_input();
	int *first = input->first;
	int *last = input->last;

	/* You may remove this output to test speed. */
	int *p = first;

	while (p < last)
		printf("%d ", *p++);

	printf("\n");
	if (task->user_data == NULL)
	{
		auto cmp = [](int a1, int a2)->bool{return a2<a1;};
		WFSortTask<int> *reverse;

		if (use_parallel_sort)
			reverse = WFAlgoTaskFactory::create_psort_task("sort", first, last,
														   cmp, callback);
		else
			reverse = WFAlgoTaskFactory::create_sort_task("sort", first, last,
														    cmp, callback);

		reverse->user_data = (void *)1;	/* as a flag */
		series_of(task)->push_back(reverse);
		printf("Sort reversely:\n");
	}
	else
		wait_group.done();
}

int main(int argc, char *argv[])
{
	size_t count;
	int *array;
	int *end;
	size_t i;

	if (argc != 2 && argc != 3)
	{
		fprintf(stderr, "USAGE: %s <count> [p]\n", argv[0]);
		exit(1);
	}

	count = atoi(argv[1]);
	array = (int *)malloc(count * sizeof (int));
	if (!array)
	{
		perror("malloc");
		exit(1);
	}

	if (argc == 3 && (*argv[2] == 'p' || *argv[2] == 'P'))
		use_parallel_sort = true;

	for (i = 0; i < count; i++)
		array[i] = rand() % 65536;
	end = &array[count];

	WFSortTask<int> *task;
	if (use_parallel_sort)
		task = WFAlgoTaskFactory::create_psort_task("sort", array, end,
													callback);
	else
		task = WFAlgoTaskFactory::create_sort_task("sort", array, end,
													callback);

	if (use_parallel_sort)
		printf("Start sorting parallelly...\n");
	else
		printf("Start sorting...\n");

	printf("Sort result:\n");
	task->start();

	wait_group.wait();
	free(array);
	return 0;
}