头文件
#include<QtConcurrent>
#include<QMutex>
QMutex是为了防止多个线程调用同一个数据文件时出错,也称互斥锁
mutex.lock();//必须成对出现
。。。
mutex.unlock();
示例
thread1 = QtConcurrent::run([=]()//开启一个新线程(创建socket通信)
{
QString s = "hello new thread!";
ui.lineEdit_2->setText(s);
thread_ = 1;//自锁
socketMat->socketConnect_server(7777);
QMutex mutex1;
while (start)
{
char imge[32];
socketMat->receive3(imge);
mutex1.lock();
for (int i = 0; i < 32; i++) {
fire[i] = imge[i];
}
mutex1.unlock();
//QString s = QString::number(fire[0]);
//ui.lineEdit->setText(s);
Sleep(100);
}
});
thread2 = QtConcurrent::run([=]()//画火点
{
QMutex mutex2;
while (start)
{
mutex2.lock();
if (fire[0] == 77 && fire[11] == 77)
{
double temp[10];
double xx, yy;
for (int i = 1; i < 11; i++) {
int j = i - 1;
temp[j] = fire[i];
}
socketcountxy(temp, &xx, &yy);
fire[0] = 0;
if (yy < 100)
{
file[0] = xx;
file[1] = yy;
drawfire(newLayer2, xx, yy);//qgis 画点--fire
}
}
mutex2.unlock();
Sleep(100);
}
});
thread3 = QtConcurrent::run([=]()//保存火点数据
{
QMutex mutex3;
newfile(filename);//以日期建立文件名
while (start)
{
mutex3.lock();
fp = fopen(filename, "a+");
if (file[0] != 0)
{
for (int j = 0; j < 2; j++)
{
fprintf(fp, "%12.6f", file[j]);
}
fprintf(fp, "\n");
}
file[0] = 0;
fclose(fp);
mutex3.unlock();
Sleep(100);
}
});
关闭线程
thread1.cancel();//关闭线程
thread2.cancel();
thread3.cancel();
初来乍到,望大佬多指正!