Files
25Sep01_ThreadMutex/code/main.cpp

48 lines
1.3 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#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;
}