1:多線程所調用的成員方法定義為static。
2:互斥鎖(pthread_mutex_t)定義在cpp文件的開頭,並且也定義為static。
3:pthread_mutex_init方法盡量在最早的時候進行調用初始化(絕對不要在初始化之后立即開始新線程,否則pthread_mutex_lock很可能會返回22的錯誤,因為此時互斥量還沒有初始化完成)。
4:pthread_mutex_destroy方法盡量在最晚的匹配的時候調用(比如構造析構——配對)。
代碼:
頭文件
public:
pthread_t tid1;
pthread_t tid2;
static void* anotherTest1(void* args);
static void* anotherTest2(void* args);
類文件:
static pthread_mutex_t mylock1;
HelloWorld::HelloWorld()
{
pthread_mutex_init(&mylock1, NULL);
}
HelloWorld::~HelloWorld()
{
pthread_mutex_destroy(&mylock1);
}
void* HelloWorld::anotherTest1(void* args)
{
int intResult1 = pthread_mutex_lock(&mylock1);
CCLOG("Result1:%d", intResult1);
for(int i=0;i<=10; i++) {
CCLOG("1-%d",i);
//sleep(1);
}
pthread_mutex_unlock(&mylock1);
return NULL;
}
void* HelloWorld::anotherTest2(void* args)
{
int intResult2 = pthread_mutex_lock(&mylock1);
CCLOG("Result2:%d", intResult2);
for(int j=0;j<=10; j++) {
CCLOG("2-%d",j);
//sleep(1);
}
pthread_mutex_unlock(&mylock1);
return NULL;
}
void HelloWorld::menuStartNewThread(CCObject* pSender)
{
pthread_create(&tid1, NULL, anotherTest1, NULL);
pthread_create(&tid2, NULL, anotherTest2, NULL);
}
