#include <QtCore>
#include <QMutex>
// Main
#include "mythread.h"
int sharedVar = 10;
QMutex mMutex;
MyThread mThread1(&mMutex, 1, &sharedVar);
MyThread mThread2(&mMutex, 2, &sharedVar);
mThread1.start(); // thread실행
mThread2.start(); // thread실행
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QtCore>
#include <QMutex>
class MyThread : public QThread
{
public:
MyThread(QMutex* mu, int myNum, int* sharedNum);
int myNumber;
int* num;
private:
QMutex* mutex
proteced:
void run();
};
#endif //MYTHREAD_H
#include "mythread.h"
#include <QtCore>
#include <QDebug>
#include <QMutexLocker>
MyThread::MyThread(QMutex* mu, int myNum, int* sharedNum)
{
mutex = mu;
myNumber = myNum;
num = sharedNum;
}
void MyThread::run()
{
qDebug() << "Thread " << myNumber << "num: " << num << "*num: " << *num;
for(int i = 0; i < 5; i++) {
mutex->lock();
(*num) = myNumber;
usleep(10);
if(*num!=myNumber){
qDebug() << "! collision ! at Thread" << myNumber;
}
qDebug() << i << "After Change, My number: " << myNumber << "*num" << *num;
mutex->unlock();
usleep(1);
}
}