SleepSort (C++)

From RAD Studio Code Examples
Jump to: navigation, search

Description

This example implements Sleep sort, an esoteric time-based sorting algorithm. The example demonstrates how to use a TCriticalSection object to synchronize output to console.

Code

#include <vcl.h>
#include <windows.h>

#pragma hdrstop
#pragma argsused

#include <tchar.h>
#include <stdio.h>

#include <Winapi.Windows.hpp>
#include <System.SysUtils.hpp>
#include <System.Classes.hpp>
#include <System.SyncObjs.hpp>

class TSleepThread : public TThread {
private:
	int FValue;
	TCriticalSection *FLock;

	void __fastcall Execute() {
		const HRESULT iniResult = CoInitializeEx(0, COINIT_MULTITHREADED);

		if (!((iniResult == S_OK) || (iniResult == S_FALSE))) {
			printf("Failed to initialize COM library.\n");
			return;
		}

		try {
			Sleep(1000 * FValue);
			FLock->Acquire();
			printf("%-3d", FValue);
			FLock->Release();
		}
		catch (Exception &ex) {
			printf("Exception inside thread.\n%ls\n", ex.Message);
		}
		CoUninitialize();
	}

public:
	TSleepThread(bool CreateSuspended, int AValue, TCriticalSection *ALock)
		: TThread(CreateSuspended) {
		FValue = AValue;
		FLock = ALock;
	}
};

#define ARR_LEN 16

int _tmain(int argc, _TCHAR* argv[]) {
	int A[ARR_LEN];
	THandle Handles[ARR_LEN];
	TThread *Threads[ARR_LEN];
	TCriticalSection *Lock;
	int i;

	// Generate random data
	for (i = 0; i < ARR_LEN; i++) {
		A[i] = Random(ARR_LEN - 1);
		printf("%-3d", A[i]);
	}
	puts("");

	// Create critical section and threads
	Lock = new TCriticalSection();
	for (i = 0; i < ARR_LEN; i++) {
		Threads[i] = new TSleepThread(true, A[i], Lock);
		Threads[i]->Start();
		Handles[i] = Threads[i]->Handle;
	}

	// Wait until threads terminate
	// This may take up to ArrLen - 1 seconds
	WaitForMultipleObjects(ARR_LEN, (void* const *)&Handles, true, INFINITE);

	// Destroy thread instances
	for (i = 0; i < ARR_LEN; i++) {
		delete Threads[i];
	}
	delete Lock;

	puts("");
	scanf("%c", A); // Data is discarded

	return 0;
}

Uses