Anyway I solved the problem as you say too and that is instantiating 100 classes with 100 threads and 100 sockets but my problem now lies in the initialization of the 100 threads as, I am using a global variable that creates problems for me for the usual race condition problem .
This is a portion of the program with the problem.
The purpose of this part of the code is only to understand the initialization of the 100 threads through a global variable. As you can see, I have not used semaphores but a sm variable that blocks the creation of the other threads to prevent the myadr variable from being overwritten by the creation of other threads.
Code: Select all
//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include "Unit1.h"
class TMyThread : public TThread
{
protected:
void __fastcall Execute();
public:
__fastcall TMyThread();
};
TMyThread *TMyTh[100];
AnsiString myadr;
bool sm;
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
}
//---------------------------------------------------------------------------
__fastcall TMyThread::TMyThread()
: TThread(true)
{
}
//---------------------------------------------------------------------------
void __fastcall TMyThread::Execute()
{
BOOL bErrorFlag = FALSE;
DWORD dwBytesWritten;
HANDLE hFile;
AnsiString fname = "dirout\\" + myadr + ".txt";
AnsiString msg;
hFile = CreateFile(fname.c_str(),
GENERIC_WRITE,
FILE_SHARE_WRITE,
NULL,
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL);
sm=false;
msg = myadr;
bErrorFlag = WriteFile( hFile,
msg.c_str(),
msg.Length(),
&dwBytesWritten,
NULL);
CloseHandle(hFile);
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
for(int i = 0; i<100; i++) {
myadr = "adr_" + IntToStr(i+1);
TMyTh[i] = new TMyThread();
TMyTh[i]->Resume();
sm=true;
while(sm);
}
Caption="created";
for(int i = 0; i<1000; i++)
{
if (TMyTh[i])
TMyTh[i]->Terminate();
}
Caption="Terminated";
}
//---------------------------------------------------------------------------