This is an attempt to run odd-even sorting from two threads without using locks. I have used a vector and split the vector logically in two halves if the size is beyond a value (Here as an example kept size 10, that means if the vector size is more than 10, then two threads will spawn and parallelize (on multi-core) sorting on the elements of the vector container. Finally, after sorting each half by two threads, another sorting will be arranged to make it finally sorted.
The Wiki contains the details about Odd-Even sorting. It's a comparison sorting. The below code snippet is a simple approach to odd-even sorting with multi-threading without having locks. No Extra space was allocated/used in this scenario.
void partBySort(std::vector<int>* vec, size_t begIndex, size_t endIndex)
{
if (begIndex == endIndex) return;
bool isSorted = false;
while (!isSorted)
{
isSorted = true;
for (size_t i = begIndex; i <= endIndex - 1; i += 2)
{
if (vec->operator[](i) > vec->operator[](i + 1))
{
std::swap(vec->operator[](i), vec->operator[](i + 1));
isSorted = false;
}
}
for (size_t i = begIndex + 1; i <= endIndex - 1; i += 2)
{
if (vec->operator[](i) > vec->operator[](i + 1))
{
std::swap(vec->operator[](i), vec->operator[](i + 1));
isSorted = false;
}
}
}
}
int main()
{
std::vector<int> vec = { 22, 0, 1, 7, 8, 23, 10, 9, 3, 11, 80, 12, 6, 13, 4, 21, 16, 18 };
//if (vec.size() <= 1) return 0;
if (vec.size() <= 10) {
partBySort(&vec, 0, vec.size() > 0 ? vec.size() - 1 : 0);
}
else {
// Creating two threads just for the demo...
std::thread oddEvenThread[2];
size_t midIndex = (vec.size() - 1) / 2;
oddEvenThread[0] = std::thread(partBySort, &vec, 0, midIndex);
oddEvenThread[1] = std::thread(partBySort, &vec, midIndex + 1, vec.size() - 1);
oddEvenThread[0].join();
oddEvenThread[1].join();
// Final sort on the full array
partBySort(&vec, 0, vec.size() - 1);
}
for (const auto& i : vec)
std::cout << i << " ";
std::cout << std::endl;
}
Comments