|
Hi
I have been looking at the examples off dll and TLS
First thing I noticed that
DWORD g_dwThreadIndex; is in global storage
It would be nice as in the IBM manuals would have registers on at entry to DllMain
I mean is the SP (register) that of the calling application
regardless if the index returned from tlsalloc lets say is 5
and then before the current thread access the storage set by tlssetvalue
another thread does a tlsallloc g_dwThreadindex becomes 6
then the first thread then does tlsgetvalue it would be using 6 instead of 5 obviously I am not understanding something
I mean if gw_dwThreadindex would be defined in the callers stack I would get it
more so is the anyway of knowing the identity of the caller I mean maybe process id or thread guess I could do a call to Startupinfo
|
|
|
|
|
We don't know which examples you've been looking at. But the whole point of thread-local storage is that it's local to the thread; one thread cannot modify a TLS variable for another thread. (At least not without jumping through several flaming hoops whilst drenched in LPG and holding a large firework.)
Each thread gets its own copy of the TLS variable. If thread A set it to 5, and thread B sets it to 6, thread A will still see it set to 5.
Thread Local Storage | Microsoft Learn[^]
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
I am refering to the following example i found in the codeproject my lack of understanding is due to the fact that gw_dwThreadIndexis defined in global storage not stack/local storage
Shrink ▲
struct ThreadData {
};
...
DWORD g_dwThreadIndex;
extern "C" BOOL WINAPI DllMain(HINSTANCE hInstance,
DWORD dwReason, LPVOID )
{
ThreadData* pData;
switch (dwReason) {
case DLL_PROCESS_ATTACH:
g_dwThreadIndex = ::TlsAlloc();
if (g_dwThreadIndex == TLS_OUT_OF_INDEXES)
return FALSE;
case DLL_THREAD_ATTACH:
pData = (ThreadData*) ::LocalAlloc(LPTR, sizeof(ThreadData));
if (pData == 0)
return FALSE;
::TlsSetValue(g_dwThreadIndex, (LPVOID) pData);
break;
case DLL_THREAD_DETACH:
pData = (ThreadData*) ::TlsGetValue(g_dwThreadIndex);
if (pData != 0)
::LocalFree((HLOCAL) pData);
break;
case DLL_PROCESS_DETACH:
pData = (ThreadData*) ::TlsGetValue(g_dwThreadIndex);
if (pData != 0)
::LocalFree((HLOCAL) pData);
::TlsFree(g_dwThreadIndex);
break;
}
return TRUE;
}
...
};
|
|
|
|
|
I'm not a C++ person, but as far as I can see, the only place you write to the g_dwThreadIndex variable is in the DLL_PROCESS_ATTACH code. According to Microsoft, that means:
The DLL is being loaded into the virtual address space of the current process as a result of the process starting up or as a result of a call to LoadLibrary . DLLs can use this opportunity to initialize any instance data or to use the TlsAlloc function to allocate a thread local storage (TLS) index.
As far as I can see, that will only ever happen once per process. And the documentation explicitly says that this is the correct time to call TlsAlloc .
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Just realized posted to wrong forum however the variable is in static or global storage the next thread that comes by can change its value thats my problem just about all the. examples for TLS and DLL s have it this way
|
|
|
|
|
ForNow wrote: the next thread that comes by can change its value
Well yes, if you do it wrong you can shoot yourself in the foot.
As far as I can see, the example you're looking at is not doing it wrong. The global variable is initialized once, in the place where the documentation says it should be initialized.
This seems to be a case of "if I stick a fork in my toaster whilst it's switched on, I can get an electric shock; therefore, all toasters are dangerous and should be banned".
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
This example works if the DLL is servicing only one address space but if it’s system DLL than I think there would be a problem ?
|
|
|
|
|
I'm not sure I quite understand what you are asking, but each thread gets its own stack (pointed at by SP) which provides all the thread local storage. It can also allocate its own storage through the normal methods. You have not really explained what g_dwThreadIndex is being used for in relation to the question. Does this all relate to some article, or specific MSDN page?
|
|
|
|
|
Richard I think I’m begging to understand the source of my confusion
First it is my understanding there are Two types off DLL one for the entire operating system in my case windows 10 and one servicing threads of one address space if it’s the former I mean that works like USER.DLL then the code example of tls wouldn’t work an I right in this ?
|
|
|
|
|
No there is only one type of DLL, which is a Dynamically Loadable Library. However, it may, or may not, be thread safe, depending on how it is created. Most (all?) of the Windows provided DLLs are thread safe. And the whole point of having DLLs is that the system only needs to load it once, to service multiple executables (i.e. address spaces). Be that as it may, I am still not sure what your concern is with regard to threads.
|
|
|
|
|
I’m sure you are right ( or else nothing would work )
I think what I have to do is have 2 exe both load the same DLL run under it under visual studio debugger and look at the address thanks
|
|
|
|
|
The actual source of the code referenced
Using Thread Local Storage in a Dynamic-Link Library - Win32 apps | Microsoft Learn[^]
Following is also relevant to see the messages.
DllMain entry point (Process.h) - Win32 apps | Microsoft Learn[^]
The code example is skipping the normal TLS semantics. So in other words it is using the first TLS index for all storage. Within the code provided.
This might follow into the following comment...
ForNow wrote: and then before the current thread access the storage set by tlssetvalue
another thread does a tlsallloc g_dwThreadindex becomes 6
Not exactly sure what you are saying there but I think you are presuming that somehow this initialization code is not thread safe. In that it might be called by multiple threads at the same time. This code method will never be called by more than one thread at a time. Additionally the 'DLL_PROCESS_ATTACH' will never be called more than once (within one process space of course.)
|
|
|
|
|
Hi
I think I’m begging to understand the source of my confusion
It is my understanding there are two types of dll’s
One services the entire os like kerenel.DLL and one just a particular address space if my code is of the former than this example is not PROCESS safe am I correct in my understanding ?
|
|
|
|
|
ForNow wrote: there are two types of dll’s
Sort of true but also not true.
When a dll is loaded the whatever loaded it decides how to use it. In one case the defining characteristic of an 'application' is that it must have a defined entry point and other defined behaviors. That is true for every operating system (not just windows and dlls.)
The code above provides a defined entry point.
Other dlls might just be libraries and they might have many 'entry' points (methods) although how each of those is defined (laid out in the dll) defines whether it can be successfully called and even how it must be called.
All of that is rather esoteric though and is almost never going to be an issue.
|
|
|
|
|
Here's some good news for anyone dealing with C++/CLI:
Stephan Lavavej recently committed changes to the VC STL which will remove a number of the roadblocks and warnings we've hit using C++/CLI in recent years. The rest of our codebase is moving to use C++20 constructs and the /clr code has had problems.
The PR: Enable /clr C++ 20 support #3194
John
|
|
|
|
|
apakah anda bisa membantu saya membuat sebuah program yang sama outputnya tetapi beda kode programnya?
tolong bantu aku
#include <iostream>
#include <string>
using namespace std;
// PROGRAM MENGHILANGKAN KARAKTER YANG SAMA DENGAN REKURSIF
void remove(string roihan){
//BASE CASE
if (roihan.length() == 1){
cout<
|
|
|
|
|
No. Partly because it's incomplete so we have no idea what it's supposed to do, partly because if you are trying to recreate an existing program, it's because the version you have can't be handed in without you presumably getting spotted for plagiarism.
And if that's the case, you won't learn anything from the exercise if you do.
Sit down with your assignment, think about it, and try designing an app from scratch. You end up learning more, and that means that your next assignment will be easier for you to complete yourself.
If you are having problems getting started at all, then this may help: How to Write Code to Solve a Problem, A Beginner's Guide[^]
And by the way: when I told you yesterday that we are an English language site, it's somewhat rude to ignore that and carry on posting in Indonesian. Being rude to people you want voluntary help from isn't a good way to start ...
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
"Common sense is so rare these days, it should be classified as a super power" - Random T-shirt
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
fungsi program adalah menghilangkan karakter yang sama sehingga karakter tersebut hanya munsul satu kali dengan menggunakan rekursif
perogram ku blm sempurnah
Google Translate: the function of the program is to remove the same character so that the character appears only once by using recursive
my program is not perfect
#include <iostream>
#include <windows.h>
using namespace std;
int main(){
char nama[1000];
int index[100];
cout<<"masukkan nama = ";
for(int i=0; i<strlen(nama); i++){
int n=0;
for(int j=0; j<strlen(nama); j++){
if(nama[i] == nama[j]){
n++;
index[j]=i;
}
}
}
for(int i=0; i<strlen(nama); i++){
if(i == index[i]){
cout<<nama[i];
}
}
}
|
|
|
|
|
This is an English language site, and we can only accept and answer questions in that language.
I have run this through Google Translate to produce a probably-good version, but you should check it and make sure it does say what you are actually asking.
And that code isn't recursive: it's iterative.
Recursion happens when a function calls itself, either directly:
int foo(int i)
{
if (i <= 1) return 1;
return i + foo(i - 1);
} Or indirectly:
int foo(int i)
{
if (i <= 1) return 1;
return i + bar(i);
}
int bar(int i)
{
return foo(i - 1);
} Your code contains one method, which you do not call yourself!
And please, do yourself a favour and indent your code more deeply - it's a lot easier to see what is going on with three or four spaces per indent rather than one. It's not a massive problem with a tiny code fragment like you show, but as your code gets bigger it becomes seriously difficult to work out what is going on!
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
"Common sense is so rare these days, it should be classified as a super power" - Random T-shirt
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Hi,
I am using vs-2015. Managed C++/Cli Windows Forms Applications. I have Form1-MdiContainer & Form2. From Form1_Button_Click() accessing Form2.
In Form2_Load() I have OLEDBConnection. For When I press Form1-Button_Click(),
First time it's working good. Also when I re-click() the same Form1-Button()
the whole application is getting closed. I analysed that when I close the OLEDBConnection, the whole program is also getting closed. And the same code working good in c#. I can't understand my mistakes..! Thanks.
Note:- For First time when I click the Form1-Button no problem it's working good. But for re-click() whole application is getting closed().
Thanks Again
My Codes
Form1-MdiContainer()
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
Form2^ MyStForm = Form2::GetForm(true, this);
MyStForm->MdiParent = this;
MyStForm->FormBorderStyle = System::Windows::Forms::FormBorderStyle::None;
MyStForm->Dock = DockStyle::Fill;
MyStForm->Show();
}
Form2-Top side
public ref class Form2 : public System::Windows::Forms::Form
{
public: static Form2^ Form2::_instance = nullptr;
public: static Form2^ Form2::GetForm(bool IsMDIChild, System::Windows::Forms::Form^ MyInstFrm) {
if (_instance == nullptr)
_instance = gcnew Form2();
if (_instance->IsDisposed)
_instance = gcnew Form2();
if (IsMDIChild)
_instance->MdiParent = MyInstFrm;
return _instance;
}
blah..blah...blah...
}
Form2-Load()
private: System::Void Form2_Load(System::Object^ sender, System::EventArgs^ e) {
String^ MyStrConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + MyExcelFile + "; Extended Properties=\"Excel 12.0; HDR=YES; OLE DB Services=-1; \"";
String^ MyExcelFile="C:\Students\Names.xlsx";
String^ MyExcelSheet = "[Sheet1$]";
String^ MySQLSelect = "select * from " + MyExcelSheet;
System::Data::OleDb::OleDbConnection^ Cn1 = nullptr;
Cn1 = gcnew System::Data::OleDb::OleDbConnection();
Cn1->ConnectionString = MyStrConn;
System::Data::OleDb::OleDbCommand^ MyCmd = nullptr;
MyCmd = gcnew System::Data::OleDb::OleDbCommand();
MyCmd->CommandText = MySQLSelect;
MyCmd->Connection = Cn1;
Cn1->Open();
System::Data::OleDb::OleDbDataAdapter^ Da1 = gcnew System::Data::OleDb::OleDbDataAdapter(MyCmd);
Da1->Fill(MyDataTable);
Cn1->Close();
if (Cn1 != nullptr){
MyCmd->Cancel();
}
MyCmd = nullptr;
Cn1 = nullptr;
}
Thanks
|
|
|
|
|
This might help re: the data adapter.
Quote: This overload of the Fill method does not implicitly call Close on the ADO object when the fill operation is complete. Therefore, always call Close when you are finished using ADO Recordset or Record objects. This makes sure that the underlying connection to a data source is released in a timely manner, and also prevents possible access violations because of unmanaged ADO objects being reclaimed by garbage collection when existing references still exist.
"Before entering on an understanding, I have meditated for a long time, and have foreseen what might happen. It is not genius which reveals to me suddenly, secretly, what I have to say or to do in a circumstance unexpected by other people; it is reflection, it is meditation." - Napoleon I
|
|
|
|
|
We've noticed that calling C functions such as abs() will call into the C Runtime implementation of abs() for a Debug build but will call into System::Math::Abs in a Release build. This was pretty unexpected as the substitution of System::Math::Abs will trigger .NET exceptions such as System::OverflowException for out of bounds conditions whereas the CRT will always return a value.
For example, this will crash in Release but exit normally in Debug. Yes, it's UB so anything is possible but it also calls System::Math::Abs even if the args are normal values. This just illustrates the exception vs non-exception.
#include <cmath>
#include <stdio.h>
int main(int, char**)
{
return std::abs(INT_MIN);
}
Does anyone have any links or good search terms for this C Runtime substitution behavior they're doing? ex. Does the loader redirect calls into System:: entrypoints for things besides abs()? I'd like to see that list so I know which calls may need to be guarded with try/catch.
I can understand that they do this swap for performance purposes and to avoid extra managed->native->managed transitions but it was news to me that this was ocurring.
John
|
|
|
|
|
Microsoft Documentation allows me to change the pull down to C++ from C# but continues to shows C# syntax
#pragma once
namespace CppTutorial {
using namespace System;
using namespace System::Threading::Tasks;
public ref class MainForm : public System::Windows::Forms::Form
{
public:
MainForm(void)
{
InitializeComponent();
}
protected:
~MainForm()
{
if (components)
{
delete components;
}
}
private:
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
void InitializeComponent(void)
{
this->SuspendLayout();
this->AutoScaleDimensions=System::Drawing::SizeF(6,13);
this->AutoScaleMode=System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize=System::Drawing::Size(284,261);
this->Name=L"MainForm";
this->Text=L"MainForm";
this->Shown+=gcnew System::EventHandler(this,&MainForm::MainForm_Shown);
this->ResumeLayout(false);
}
#pragma endregion
public:
static void Body(int index)
{
int test=0;
}
delegate void MyDelegate(int index);
System::Void MainForm_Shown(System::Object^ sender,System::EventArgs^ e)
{
MyDelegate ^body=gcnew MyDelegate(MainForm::Body);
ParallelLoopResult ^result=Parallel::For(0,10,(System::Action <int> ^)body);
}
};
}
I know its all a bit bodged but its the only way i could get it to compile and link but the problem is obvious run time crash
System.InvalidCastException:
Unable to cast object of type 'MyDelegate' to type 'System.Action`1[System.Int32]'.
in MC++/CLI i cant find the right syntax to use for
ParallelLoopResult ^result=Parallel::For( without casting to Action
there is no generic delegate in the overides
Is there any MC++/CLI people left out there that can help or offer any other way to paralleize a for loop
i tried the old parallel_for(x,y,z){ "do stuff here" } way but
i couldnt get that very far with that either
i prefer to stick with .net but this delegate stuff omg :¬( im to old hehe
Thanks for even bothering to read this
modified 28-Jul-22 4:36am.
|
|
|
|
|
As the error says, you can't create a delegate of one type, and then cast it to a different type.
Change your code to create the correct delegate type in the first place, and remove the cast.
System::Action <int> ^body = gcnew System::Action <int>(MainForm::Body);
ParallelLoopResult ^result = Parallel::For(0, 10, body);
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
 Thank you very much Richard
If MS docs had C++ version of this i would have not neded to bother you
I was very confused as i dont do delegates if i can avoid it
Very happy some C++/CLR people still exist
ill mark as solved
Here is the Final working MainForm() showing cross thread update of textBox, Random, and usage of other Member funtions
This is here to help anyone that is as bad at this overcomplicated Parallel coding in C++/CLR (my opinion should be easier)
"Parallel::For" - intellisense still moans about 2 or more overloads of it but who cares anyway, no one :¬)
namespace CppTutorial {
using namespace System;
using namespace System::Threading::Tasks;
using namespace System::Windows::Forms;
public ref class MainForm : public System::Windows::Forms::Form
{
public:
MainForm(void)
{
InitializeComponent();
}
protected:
~MainForm()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::TextBox ^textBox1;
protected:
private:
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
void InitializeComponent(void)
{
this->textBox1=(gcnew System::Windows::Forms::TextBox());
this->SuspendLayout();
this->textBox1->Dock=System::Windows::Forms::DockStyle::Fill;
this->textBox1->Location=System::Drawing::Point(0,0);
this->textBox1->Multiline=true;
this->textBox1->Name=L"textBox1";
this->textBox1->Size=System::Drawing::Size(563,451);
this->textBox1->TabIndex=0;
this->AutoScaleDimensions=System::Drawing::SizeF(6,13);
this->AutoScaleMode=System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize=System::Drawing::Size(563,451);
this->Controls->Add(this->textBox1);
this->Name=L"MainForm";
this->Text=L"MainForm";
this->Shown+=gcnew System::EventHandler(this,&MainForm::MainForm_Shown);
this->ResumeLayout(false);
this->PerformLayout();
}
#pragma endregion
public:
static MainForm ^staticmain;
Random ^rand1;
static void Body(int index)
{
int r=staticmain->rand1->Next(1000000);
for(int i=0;i<r;i++){}
staticmain->textBox1->AppendText("i: "+Convert::ToString(index)+" - r: "+Convert::ToString(r)+"\r\n");
staticmain->AnotherMethod();
}
System::Void MainForm_Shown(System::Object^ sender,System::EventArgs^ e)
{
staticmain=this;
rand1=gcnew Random();
textBox1->CheckForIllegalCrossThreadCalls=false;
System::Action <int> ^body = gcnew System::Action <int> (MainForm::Body);
ParallelLoopResult ^result = Parallel::For(0, 20, body);
}
void AnotherMethod()
{
int test=1;
}
};
}
modified 29-Jul-22 3:41am.
|
|
|
|