Files
Obsidian/threadclock.cpp
2025-08-23 15:15:57 +08:00

171 lines
3.2 KiB
C++

#include "threadclock.h"
#include "GlobalData.h"
#include <QMutex>
#include <QDebug>
#include <QReadWriteLock>
#include <QWaitCondition>
#include <QSemaphore>
QMutex mutex(QMutex::Recursive);//默认那种方式不行,另一个线程不会阻塞等待
QReadWriteLock rwLock(QReadWriteLock::Recursive);
QMutex mutexCon;//配合等待条件,不能用上面那种
QWaitCondition condition;
//信号量
QSemaphore sem(8);
ThreadClock::ThreadClock(QObject *parent)
: QThread{parent}
{
;
}
QString ThreadClock::name() const
{
return m_name;
}
void ThreadClock::setName(const QString &newName)
{
m_name = newName;
}
#if 1
void ThreadClock::run()
{
mutex.lock();
while (g_count < 5) {
g_count++;
qDebug() << m_name << g_count;
sleep(1);
}
g_count = 0;
mutex.unlock();
}
#endif
#if 0
/*
"2thread" 2
"1thread" 1
"1thread" 4
"2thread" 4
"2thread" 0
"2thread" 1
"2thread" 2
"2thread" 3
"2thread" 4
"2thread" 5
*/
//可见读锁在线程之间是不阻塞的
void ThreadClock::run()
{
rwLock.lockForRead();
while (g_count < 5) {
g_count++;
qDebug() << m_name << g_count;
sleep(1);
}
g_count = 0;
rwLock.unlock();
}
#endif
#if 0
/*
"1thread" 1
"1thread" 2
"1thread" 3
"1thread" 4
"1thread" 5
"2thread" 1
"2thread" 2
"2thread" 3
"2thread" 4
"2thread" 5
*/
//读写锁之间是阻塞的
void ThreadClock::run()
{
if (m_name == "1thread") {
rwLock.lockForRead();
}else {
rwLock.lockForWrite();
}
while (g_count < 5) {
g_count++;
qDebug() << m_name << g_count;
sleep(1);
}
g_count = 0;
rwLock.unlock();
}
#endif
#if 0
//QWaitCondition的使用 注意:无限循环
void ThreadClock::run()
{
//生产者
if (m_name == "1thread") {
while (true) {
mutexCon.lock();
g_count++;//生产
qDebug() << m_name << g_count;//生产的数据
condition.wakeAll();//唤醒其它线程(可以消费)
mutexCon.unlock();
}
}else{//消费者
while (true) {
mutexCon.lock();
while (g_count <= 0) {//说明生产者还没有生产数据
condition.wait(&mutexCon);//等待生产者生产完成,解锁
}
qDebug() << m_name << g_count;//消费的数据
g_count--;//消费
mutexCon.unlock();
}
}
}
#endif
/*
"1thread" 0
"1thread" 1
"1thread" 2
"1thread" 3
"1thread" 4
"1thread" 5
"1thread" 6
"1thread" 7 这里已经满了,无法生产了
"2thread" 0 消费一个之后
"1thread" 8 才能继续生产
"2thread" 1
"1thread" 9
"2thread" 9
*/
#if 0
//信号量的使用 注意:无限循环
void ThreadClock::run()
{
//生产者
if (m_name == "1thread") {
while (true) {
sem.acquire(1);
g_bufferData[g_count % 8] = '0' + g_count;//这里把g_count当成索引
qDebug() << m_name << g_bufferData[g_count % 8];//生产的数据
g_count++;
}
}else{//消费者
while (true) {
qDebug() << m_name << g_bufferData[g_count % 8];//消费的数据
sem.release(1);
}
}
}
#endif