关于CB6多线程编程,我要实现一个类似unix里pthread_mutex_t功能的东西,应该用什么?
如题,请教了,如果有多线程的例子,包括共享和同步的最好,cb自带的那个例子太简单了。
[解决办法]
Windows API就有类似的东西
Mutex
[解决办法]
C++Builder本身就带了
TCriticalSection
[解决办法]
互斥Mutex
[解决办法]
随便写了一个,控制台的,楼主看看合要求不
//---------------------------------------#include <vcl.h>#include <SyncObjs.hpp>#include <iostream>#pragma hdrstop//---------------------------------------#pragma argsusedclass TShowData{private: int m_iValue; TCriticalSection *m_cs; //这个是进程内同步的,如果要进程间同步用Mutex,API: CreateMutex,CloseHandle,WaitForSingleObject,ReleaseMutexpublic: TShowData(): m_iValue(0){ m_cs = new TCriticalSection; } ~TShowData(){ delete m_cs; } void Print(int id) { using namespace std; m_cs->Enter(); //同步, 因为m_iValue是线程间共享的,而且cout也是非线程安全的 cout<< "ID: " << id << "; Value: " << m_iValue++ <<endl; m_cs->Leave(); }};class TMyThread : public TThread{private: TShowData &m_sdDemo; int m_nID;protected: void __fastcall Execute();public: __fastcall TMyThread(TShowData &SD,int id) :TThread(false),m_sdDemo(SD),m_nID(id) { FreeOnTerminate=true; // 线程执行完后自动delete自己 }};void __fastcall TMyThread::Execute(){ for(int i=0; i<10 && !Terminated; i++) m_sdDemo.Print(m_nID); // 调用Print 10次}int main(int argc, char* argv[]){ TShowData sd; TMyThread *mt1=new TMyThread(sd,1); // 多线程调用sd里的Print TMyThread *mt2=new TMyThread(sd,2); TMyThread *mt3=new TMyThread(sd,3); system("pause"); return 0; }//---------------------------------------