salut j'ai essayé de communiquer 2 threads par l'intermédiaire d'une QSharedMemory :
Thread1 --> écrire dans le segment mémoire
Thread2 --> lire de ce segment
vu que chaque Thread est dans une classe différente!
voici le code :
Thread 1: (création et écriture)
Thread 2 :(lecture du segment)Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28 #include "thread.h" #include <QtCore> #include <QDebug> Thread::Thread() { } void Thread::run() { qDebug() << this->name <<"Runned thread2 MSG!!!"; QSharedMemory shared("memory"); if(!shared.create(1024,QSharedMemory::ReadWrite)) { qDebug() << "segment not be create!!!"; } qDebug() << "segment created successfully"; shared.lock(); char *to = (char*)shared.data(); char *text = "SND_SV1_LCH_DATA"; memcpy(to, text, strlen(text)+1); shared.unlock(); qDebug()<<"thread2 terminated"; }
la classe main:Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25 #include "mythread.h" #include <QtCore> #include <QDebug> MyThread::MyThread() { } void MyThread::run() { qDebug() << this->name <<"Running ..."; sleep(3); QSharedMemory shared("memory"); shared.attach(QSharedMemory::ReadWrite); shared.lock(); char *to = (char*)shared.data(); qDebug() << "the content of segment is : " << to; shared.unlock(); shared.detach(); qDebug() << "segment is deleted"; }
Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33 #include <QCoreApplication> #include "mythread.h" #include "thread.h" int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); MyThread mThread1; mThread1.name = "mThread1"; Thread mThread2; mThread2.name = "mThread2"; QMutex mutex; mutex.lock(); mThread2.start(); mutex.unlock(); sleep(5); mutex.lock(); mThread1.start(); mutex.unlock(); //mThread1.Stop = false; return a.exec(); }