TSpinWait (C++)
Description
The following example illustrates the usage of a TSpinWait record. This is a console application, where the main thread waits in a spin-loop until a global variable is set by a secondary thread.
Code
#include <vcl.h>
#pragma hdrstop
#include <tchar.h>
#include <Classes.hpp>
#include <iostream>
using namespace std;
#pragma argsused
// ---------------------------------------------------------------------------
static bool flag;
// ---------------------------------------------------------------------------
class TThreadCause : public TThread {
private:
void __fastcall Execute() {
Sleep(100); // 100 milliseconds
flag = true;
}
public:
TThreadCause(bool createSuspended) : TThread(createSuspended) {
}
};
// ---------------------------------------------------------------------------
int _tmain(int argc, _TCHAR* argv[]) {
flag = false;
TThread *cause = new TThreadCause(true);
cause->Start();
TSpinWait spinner;
spinner.Reset();
while (flag == false) {
cout << spinner.Count << endl;
spinner.SpinCycle();
}
cout << spinner.Count << endl;
cout << "flag is " << flag << endl; // displays "flag is 1"
return 0;
}
Uses
- SysUtils.TSpinWait ( fr | de | ja )
- SysUtils.TSpinWait.SpinCycle ( fr | de | ja )