到目前为止,我有这样的代码:为什么TMutex方法Acquire()不锁定互斥锁?
****SimpleForm.h****
class TForm1 : public TForm
{
__published: // IDE-managed Components
TMemo *Memo1;
TButton *Button1;
void __fastcall Button1Click(TObject *Sender);
private: // User declarations
TMutex *mtx;
public: // User declarations
__fastcall TForm1(TComponent* Owner);
};
****SimpleForm.cpp****
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
mtx = new TMutex(true);
WorkerThread *wt = new WorkerThread(false, mtx);
}
void __fastcall TForm1::Button1Click(TObject *Sender)
{
mtx->Acquire();
Memo1->Lines->Add("Locked...");
mtx->Release();
}
****WorkerThread.h****
class WorkerThread : public TThread
{
private:
TMutex *mtx;
protected:
void __fastcall Execute();
public:
__fastcall WorkerThread(bool CreateSuspended, TMutex *mtx);
void __fastcall CheckLock();
};
****WorkerThread.cpp****
__fastcall WorkerThread::WorkerThread(bool CreateSuspended, TMutex *mtx)
: TThread(CreateSuspended)
{
this->mtx = mtx;
}
void __fastcall WorkerThread::Execute()
{
while(true){
Sleep(1000);
Synchronize(CheckLock);
}
}
void __fastcall WorkerThread::CheckLock(){
this->mtx->Acquire();
Form1->Memo1->Lines->Add("Locked from thread");
//this->mtx->Release();
}
的问题是,mtx->Acquire()
没有锁定一个互斥体,当我发表意见mtx->Release()
,没有什么运行期间发生变化,两个线程可以同时访问同一个共享资源,女巫不是我想要的。我在Linux环境中使用p_threads,并且当互斥锁被锁定时,其他线程等待它变为可用。我如何使用C++ CodeGear 2009实现相同的结果?
刚刚用TCriticalSection测试过,结果相同。我检查了两个线程中的TMutext/TCriticalSection对象是相同的,但不知何故我无法让它们锁定。 –
他们确实锁定。我日复一日地使用这些物体。还有一些我看不到的东西。 –
我编辑了我的初始代码片段。现在完整的代码在那里。注意注释的mtx-> Release();行,为什么主线程仍然可以成功锁定互斥锁? –