新增:实现 ThreadMutex 类
This commit is contained in:
47
code/main.cpp
Normal file
47
code/main.cpp
Normal 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;
|
||||
}
|
||||
Reference in New Issue
Block a user