新增:实现 ThreadMutex 类

This commit is contained in:
2025-09-01 16:35:25 +08:00
commit 9958d730d9
8 changed files with 259 additions and 0 deletions

53
code/ThreadMutex.cpp Normal file
View File

@ -0,0 +1,53 @@
#include "ThreadMutex.h"
int ThreadMutex::XLockGetTestFlag(void)
{
return mCurTestFlag_;
}
bool ThreadMutex::XLockTryLock(int tInputWait10Ms, int tInputTestFlag)
{
int tTempN;
if (tInputWait10Ms <= 0)
{
while (1)
{
if (0 == pthread_mutex_trylock(&mMutex_))
{
mCurTestFlag_ = tInputTestFlag;
return true;
}
usleep(1000 * 5);
}
}
else
{
for (tTempN = 0; tTempN < tInputWait10Ms; tTempN++)
{
if (0 == pthread_mutex_trylock(&mMutex_))
{
mCurTestFlag_ = tInputTestFlag;
return true;
}
usleep(1000 * 5);
}
return false;
}
}
void ThreadMutex::XLockUnLock(void)
{
mCurTestFlag_ = -1;
pthread_mutex_unlock(&mMutex_);
}
ThreadMutex::ThreadMutex(void)
{
pthread_mutex_init(&mMutex_, NULL);
}
ThreadMutex::~ThreadMutex()
{
pthread_mutex_destroy(&mMutex_);
}

21
code/ThreadMutex.h Normal file
View File

@ -0,0 +1,21 @@
#ifndef THREADMUTE_H
#define THREADMUTE_H
#include <pthread.h>
#include <unistd.h>
class ThreadMutex
{
public:
int XLockGetTestFlag(void);
bool XLockTryLock(int tInputWait10Ms, int tInputTestFlag = -1);
void XLockUnLock(void);
ThreadMutex(void);
~ThreadMutex();
private:
pthread_mutex_t mMutex_;
int mCurTestFlag_;
};
#endif

47
code/main.cpp Normal file
View File

@ -0,0 +1,47 @@
#include "ThreadMutex.h"
#include <iostream>
ThreadMutex gThreadMutex;
void *threadFunc(void *arg)
{
int tTemID = *(int *)arg;
for (int tTempN = 0; tTempN < 3; ++tTempN)
{
if (gThreadMutex.XLockTryLock(100, tTemID))
{
std::cout << "[Thread " << tTemID << "] got lock, iteration " << tTempN << std::endl;
usleep(1000 * 200); // 模拟操作200ms
gThreadMutex.XLockUnLock();
std::cout << "[Thread " << tTemID << "] released lock, iteration " << tTempN << std::endl;
}
else
{
std::cout << "[Thread " << tTemID << "] failed to get lock, iteration " << tTempN << std::endl;
}
usleep(1000 * 50); // 等待 50ms 再尝试下一轮
}
return nullptr;
}
int main(int argc, char **argv)
{
const int tTemThreadNum = 3;
pthread_t threads[tTemThreadNum];
int threadIds[tTemThreadNum] = {1, 2, 3};
/* 创建线程 */
for (int tTempN = 0; tTempN < tTemThreadNum; ++tTempN)
{
pthread_create(&threads[tTempN], nullptr, threadFunc, &threadIds[tTempN]);
}
/* 等待线程结束 */
for (int tTempN = 0; tTempN < tTemThreadNum; ++tTempN)
{
pthread_join(threads[tTempN], nullptr);
}
std::cout << "All threads finished." << std::endl;
return 0;
}