TLightweightSemaphore (C++)

From RAD Studio Code Examples
Jump to: navigation, search

Description

The following example illustrates the use of the TLightweightSemaphore class. (You can actually use here the TSemaphore class instead of TLightweightSemaphore, with minor code modifications.)

Three threads are created. Each of them is trying to write in the console the (approximate) execution time interval (start and end). The console, in this case, is the critical resource. The semaphore that is created to coordinate the write operations is initialized with value 1 (which means that it behaves like a mutex). You may see that the intervals displayed do not overlap, which indicates that the threads are synchronized when writing in to the console.

Code

#include <vcl.h>
#pragma hdrstop

#include <tchar.h>
#include <Classes.hpp>
#include <DateUtils.hpp>
#include <iostream>
#include <string>
using namespace std;
// ---------------------------------------------------------------------------

#pragma argsused
static const int timestep = 100; // Milliseconds
static TLightweightSemaphore *consoleSemaphore;
#define NUMBER_OF_THREADS 3
static TThread *consumer[NUMBER_OF_THREADS];

class TThreadConsumer : public TThread {
private:
	void __fastcall Execute() {
		consoleSemaphore->WaitFor();

		TDateTime datetime = Time();
		cout << "[" << SecondOf(datetime) << ":" << MilliSecondOf(datetime);

		Sleep(timestep);

		datetime = Time();
		cout << "; " << SecondOf(datetime) << ":" << MilliSecondOf(datetime)
			<< "]" << endl;

		consoleSemaphore->Release();
	}

public:
	TThreadConsumer(bool createSuspended) : TThread(createSuspended) {
		// cout << "Thread ctor" << endl;
	}
};

int _tmain(int argc, _TCHAR* argv[]) {
	consoleSemaphore = new TLightweightSemaphore(1, 1 /* Max. Count */);

	// Start threads
	for (int i = 0; i < NUMBER_OF_THREADS; i++) {
		consumer[i] = new TThreadConsumer(true);
		consumer[i]->Start();
	}

	// Sleep until all the threads are certainly finished
	Sleep(2 * NUMBER_OF_THREADS * timestep);

	return 0; // Put breakpoint here to see the console output.
}

Sample console output

[42:406; 42:516]
[42:516; 42:609]
[42:609; 42:719]

Uses