0

may I have the community's opinion here. I have an application in which I have multiple threads accessing a member of a (this) class, the class that invoked the thread itself. The problem is that when the new thread adds an element in a LinkedList member, I can see that the LinkedList's count is increased to 1 as a result of the added element, however in the main thread the changes made by the new thread was not reflected. I even passed the reference of the current object to ParameterizedThreadStart, but it's still not working.

illustration:

ParameterizedThreadStart^ pReceiveProc = gcnew ParameterizedThreadStart(this, &ActualClass::Receive);
Thread^ pReceiveThread = gcnew Thread(pReceiveProc);
pReceiveThread->Start(this); // passed the current instance

the thread method:

void Receive(Object^ pObj) {
    ActualClass^ l_Cls = dynamic_cast<ActualClass^>(pObj);
    l_Cls->MyLinkList->AddLast("test");
    Console::WriteLine("{0}", l_Cls->MyLinkList->Count); //outputs 1
}

but if I access MyLinkList from the main thread:

void MethodMainThread(){
    Console::WriteLine("{0}", MyLinkList->Count); //outputs 0
}

A static member solution is not an option.

4

2 に答える 2

1

最も可能性が高いのは、セカンダリ スレッドがプリエンプトされ、メイン スレッドがカウントをチェックしてから、セカンダリ スレッドがオブジェクトを追加し、シグナリングを使用して、セカンダリ スレッドが操作を完了するまでメイン スレッドを待機させることです。

于 2013-03-11T05:54:44.323 に答える
0

そのようにスレッド間でデータを共有することはできません。これに対する簡単なアプローチは、'lock' ステートメントを使用することです。それはかなり簡単で、ここに良い説明があります。

于 2013-03-11T05:48:42.860 に答える