-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathknapsack_parallel.cpp
285 lines (265 loc) · 10.9 KB
/
knapsack_parallel.cpp
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
#include <bits/stdc++.h>
#include "core/utils.h"
#include <atomic>
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <sstream>
#include <thread>
#define DEFAULT_CAPACITY "50"
void knapSack(
const int total_capacity,
const std::vector<int> &weights,
const std::vector<int> &profits,
const int num_items,
const uint thread_id,
const uint num_threads,
const uint granularity,
std::vector<int> &arr1,
std::vector<int> &arr2,
std::vector<int> &arr3,
std::atomic<uint> &next_initial_weight_range,
CustomBarrier &the_wall
) {
uint initial_weight_range = thread_id * granularity;
// Counter to rotate what array is being used
uint counter = 0;
for (int i = 1; i < num_items + 1; i++) {
while(true) {
if (counter == 0) {
for (int w = initial_weight_range; (w < granularity + initial_weight_range && w <= arr2.size()); w++) {
// Finding the maximum value
// Check if capacity could hold weight of new item
if (w >= weights[i - 1]) {
arr2[w] = std::max(arr1[w], arr1[w - weights[i - 1]] + profits[i - 1]);
} else {
arr2[w] = arr1[w];
}
}
} else if (counter == 1) {
for (int w = initial_weight_range; (w < granularity + initial_weight_range && w <= arr3.size()); w++) {
// Finding the maximum value
// Check if capacity could hold weight of new item
if (w >= weights[i - 1]) {
arr3[w] = std::max(arr2[w], arr2[w - weights[i - 1]] + profits[i - 1]);
} else {
arr3[w] = arr2[w];
}
}
} else {
for (int w = initial_weight_range; (w < granularity + initial_weight_range && w <= arr1.size()); w++) {
// Finding the maximum value
// Check if capacity could hold weight of new item
if (w >= weights[i - 1]) {
arr1[w] = std::max(arr3[w], arr3[w - weights[i - 1]] + profits[i - 1]);
} else {
arr1[w] = arr3[w];
}
}
}
// Check if there are more weights to be processed
if (next_initial_weight_range.load() * granularity > total_capacity) {
// barrier
the_wall.wait();
uint current_next = next_initial_weight_range.load();
while (!next_initial_weight_range.compare_exchange_weak(current_next, num_threads));
break;
}
// Get next initial weight range...
while (true) {
uint current_next = next_initial_weight_range.load();
uint next = current_next + 1;
if (next_initial_weight_range.compare_exchange_weak(current_next, next)) {
initial_weight_range = current_next * granularity;
break;
}
}
}
initial_weight_range = thread_id * granularity;
counter++;
if (counter > 2) {
counter = 0;
}
}
// Make sure that the final result is in arr1
if (thread_id ==0) {
if (counter == 1) {
arr1[total_capacity] = arr2[total_capacity];
} else if (counter == 2) {
arr1[total_capacity] = arr3[total_capacity];
}
}
}
void knapSack_default(
const int total_capacity,
const std::vector<int> &weights,
const std::vector<int> &profits,
const int num_items,
const uint thread_id,
std::vector<int> &arr3,
std::vector<int> &arr2,
std::vector<int> &arr1,
CustomBarrier &the_wall,
const uint initial_index,
const uint end_index
) {
timer t1;
double total_time_waiting=0;
// Initialize counter to rotate the array being used
uint counter = 0;
for (int i = 1; i < num_items + 1; i++) {
if (counter == 0) {
for (int w = initial_index; (w < end_index && w < arr2.size()); w++) {
// Finding the maximum value
// Check if capacity could hold weight of new item
if (w >= weights[i - 1]) {
arr2[w] = std::max(arr1[w], arr1[w - weights[i - 1]] + profits[i - 1]);
} else {
arr2[w] = arr1[w];
}
}
} else if(counter == 1){
for (int w = initial_index; (w < end_index && w < arr3.size()); w++) {
// Finding the maximum value
// Check if capacity could hold weight of new item
if (w >= weights[i - 1]) {
arr3[w] = std::max(arr2[w], arr2[w - weights[i - 1]] + profits[i - 1]);
} else {
arr3[w] = arr2[w];
}
}
} else {
for (int w = initial_index; (w < end_index && w < arr1.size()); w++) {
// Finding the maximum value
// Check if capacity could hold weight of new item
if (w >= weights[i - 1]) {
arr1[w] = std::max(arr3[w], arr3[w - weights[i - 1]] + profits[i - 1]);
} else {
arr1[w] = arr3[w];
}
}
}
// Operate counter to know what arrays to use next
counter++;
if (counter > 2) {
counter = 0;
}
// Synchronize threads
t1.start();
the_wall.wait();
total_time_waiting+=t1.stop();
}
// Make sure that the final result is in arr1
if (thread_id ==0) {
if (counter == 1) {
arr1[total_capacity] = arr2[total_capacity];
} else if (counter == 2) {
arr1[total_capacity] = arr3[total_capacity];
}
}
printf("In thread %u start_index=%u and end_index=%u it waited at wall for %.4f seconds\n", thread_id, initial_index, end_index, total_time_waiting);
}
// Function to find the maximum values
int knapSack_parallel(
const int capacity,
const std::vector<int> &weights,
const std::vector<int> &profits,
const int num_items,
const uint num_threads,
const uint granularity
) {
// 2d matrix where rows are items and columns are weights
std::vector<int> arr1(capacity+1, 0);
std::vector<int> arr2(capacity+1, 0);
std::vector<int> arr3(capacity+1, 0);
// Initial index for next weight range
// Index increases according to granularity and threads take it when they are done with a weight range
std::atomic<uint> next_initial_weight_range;
next_initial_weight_range.store(num_threads);
std::vector<std::thread> threads;
threads.reserve(num_threads);
CustomBarrier the_wall(num_threads);
timer t1;
t1.start();
if (granularity == 0){
printf("Running default 1\n");
uint capacity_per_thread = (capacity+1)/num_threads;
uint start_index = 0;
uint end_index = start_index+capacity_per_thread+(capacity+1)%num_threads;
std::cout << "Size of vectors is: " << arr3.size() << ", " << arr1.size() << ", " << arr2.size() << std::endl;
for (uint thread_id = 0; thread_id < num_threads; thread_id++) {
if (thread_id == num_threads - 1) {
end_index = capacity + 1;
}
threads.emplace_back([capacity, &weights, &profits, num_items, thread_id, &arr1, &arr2, &arr3, &the_wall, start_index, end_index](){
knapSack_default(capacity, weights, profits, num_items, thread_id, arr1, arr2, arr3, the_wall, start_index, end_index);});
start_index = end_index;
end_index = start_index+capacity_per_thread;
}
} else {
printf("Running with granularities\n");
for (uint thread_id = 0; thread_id < num_threads; thread_id++) {
threads.emplace_back([capacity, &weights, &profits, num_items, thread_id, num_threads, granularity, &arr1, &arr2, &arr3, &next_initial_weight_range, &the_wall](){
knapSack(capacity, weights, profits, num_items, thread_id, num_threads, granularity, arr1, arr2, arr3, next_initial_weight_range, the_wall);});
}
}
for (auto &thread: threads) {
thread.join();
}
auto execution_time = t1.stop();
// Returning the maximum value of knapsack
printf("Maximum value of knapsack is %d\nTook %f seconds\n", arr1[capacity], execution_time);
//std::cout << arr1[num_items][capacity] << std::endl;
return arr1[capacity];
}
// Driver code
int main(int argc, char* argv[]) {
//init command line args
cxxopts::Options options("Read input file",
"Read input file for knapsack problem");
options.add_options(
"custom",
{
{"fName", "File Name",
cxxopts::value<std::string>()->default_value("knapsack_input.txt")},
{"capacity", "Capacity of the knapsack",
cxxopts::value<int>()->default_value(DEFAULT_CAPACITY)},
{"numThreads", "Number of threads",
cxxopts::value<uint>()->default_value(DEFAULT_CAPACITY)},
{"granularity", "Granularity for threads to work in",
cxxopts::value<uint>()->default_value(DEFAULT_CAPACITY)},
});
auto cl_options = options.parse(argc, argv);
std::string file_name = cl_options["fName"].as<std::string>(); // acquire file from where to read input
int capacity = cl_options["capacity"].as<int>(); // acquire capacity of knapsack
uint num_threads = cl_options["numThreads"].as<uint>();
uint granularity = cl_options["granularity"].as<uint>();
// Open the file
std::ifstream file(file_name); // Open the file
if (!file) {
std::cerr << "Unable to open file.\n";
return 1;
}
std::string line;
std::getline(file, line); // Read the first line for the number of tuples
uint num_tuples = std::stoi(line);
std::vector<int> values;
std::vector<int> weights;
while (std::getline(file, line)) { // Read each line, one I/O per line
std::istringstream line_stream(line); // get line stream for parsing in memory
char ch;
int value, weight;
line_stream >> ch >> value >> ch >> weight >> ch; // Parse the tuple format (1, 2)
values.push_back(value); // Add the value to the vector
weights.push_back(weight); // add weight to the vector
}
file.close(); // Close the file
std::cout << "Starting knapsack problem\n"
<< "Capacity: " << capacity << "\n"
<< "Num Items: " << num_tuples << "\n"
<< "Num threads: " << num_threads << "\n"
<< "Granularity: " << granularity << std::endl;
knapSack_parallel(capacity, weights, values, num_tuples, num_threads, granularity);
return 0;
}