@JonB said in Mutex, please explain what's wrong:
If this is your precise objective I think you cannot achieve this with a single mutex. It seems to me you have 3 alternatives:
Use semaphores. I see this is the "accepted" solution at How
Thanx, Semaphors are on the list of my styding. Also I have fully resolved the problem by numerating threads and blocking "last processed thread" to work twice:
#include <QCoreApplication>
#include <QDebug>
#include <QMutex>
#include <QThread>
#include <QObject>
#include <QDebug>
#include <QMutexLocker>
QMutex mutex;
int count = 0;
int last_thread_num = 0;
//=================
class thread1_tst : public QThread
{
Q_OBJECT
public:
int _thread_num;
int& _last_thread_num;
explicit thread1_tst(int thead_num, int& last_thread_num, QObject *parent = nullptr);
void run();
void my_work();
};
//------------------------------
thread1_tst::thread1_tst(int thread_num, int& last_thread_num, QObject *parent)
: QThread{parent}, _thread_num(thread_num), _last_thread_num(last_thread_num)
{}
//------------------------------
void thread1_tst::run()
{
while(1)
{
if(_thread_num != _last_thread_num)
my_work();
else
msleep(1);
}
}
//------------------------------
void thread1_tst::my_work()
{
{
QMutexLocker locker(&mutex);
for(int i=0; i < 5; i++)
qDebug() << "thread 1 out: count=" << count++ << " (" << i << ")";
qDebug() << "----end 1 -----";
}
msleep(1000);
last_thread_num = _thread_num;
}
//=================
class thread2_tst : public QThread
{
Q_OBJECT
public:
int _thread_num;
int& _last_thread_num;
explicit thread2_tst(int thead_num, int& busy_fl, QObject *parent = nullptr);
void run();
void my_work();
};
thread2_tst::thread2_tst(int thread_num, int& last_thread_num, QObject *parent)
: QThread{parent}, _thread_num(thread_num), _last_thread_num(last_thread_num)
{}
void thread2_tst::run()
{
while(1)
{
if(_thread_num != _last_thread_num)
my_work();
else
msleep(1);
}
}
//------------------------------
void thread2_tst::my_work()
{
{
QMutexLocker locker(&mutex);
for(int i=0; i < 5; i++)
qDebug() << "thread 2 out: count=" << count++ << " (" << i << ")";
qDebug() << "----end 2 -----";
}
msleep(1000);
last_thread_num = _thread_num;
}
//=============================
thread1_tst thread1(0, last_thread_num); //make threads enumerated
thread2_tst thread2(1, last_thread_num);
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
thread1.start(); thread2.start();
return a.exec();
}
#include "waitconditions.moc"