QT console 模式下怎么实现多线程?

lwy723 2020-04-21 07:31:42
最近在模拟memory allocator的功能,组里有人想根据创建的process的执行时间来按时删除执行完的process,但因为mian function里面我是依照while循环和cin来创建process的,好像没办法实现在等待cin过程中的时间计算。感觉只能用多线程来实现,一个线程来计算时间,一个线程来执行cin等待,但我在实现简易版的时候,窗口模式下好像没办法同时进行。

这个是我定义的Mythread,_______________________________________

#ifndef MYTHREAD_H
#define MYTHREAD_H

#include <QThread>
#include <QDebug>
#include <iostream>
#include <vector>
#include <map>
#include <QTimer>
#include <ctime>
#include <string>
using namespace std;

class MyThread : public QThread
{
Q_OBJECT;

public:
MyThread(vector<int> & vec_1, time_t &start, time_t &mid){
refer_vec = &vec_1;
refer_start = &start;
refer_mid = ∣
cout<<"give me the size"<<endl;
}


void run(){
while(is_runnable){

*refer_mid = time(nullptr);
if((*refer_mid) > (*refer_start) + 3){
(*refer_vec).erase((*refer_vec).begin());
*refer_start = time(nullptr);
}

if((*refer_vec).size() == 0){
is_runnable = false;
}
}

if(is_runnable == false){
return;
}

}

void stop_sub(){
is_runnable = false;
}

private:
bool is_runnable = true;
vector<int> *refer_vec;
time_t *refer_start;
time_t *refer_mid;

};

#endif // MYTHREAD_H



下面是main function:_____________________________________

#include <ctime>
#include <QCoreApplication>
#include <iostream>
#include <QTimer>
#include <QObject>

#include "mythread.h"
using namespace std;


int main(){
time_t start= time(nullptr);
time_t end;

vector<int> vec_1;
vec_1.push_back(4);
vec_1.push_back(5);
vec_1.push_back(6);
vec_1.push_back(9);
vec_1.push_back(8);
vec_1.push_back(10);
vec_1.push_back(19);



string yes_no;
string cre_free;
string size;

while(true){
time_t mid = time(nullptr);


MyThread abcd(vec_1,start,mid);
abcd.start();
abcd.run();

getline(cin,yes_no);
if(yes_no == "yes"){
abcd.stop_sub();
abcd.quit();
abcd.wait();
break;
}else{
abcd.stop_sub();
abcd.quit();
abcd.wait();
}


}
}
我的想法是while 循环每次都开启一个新线程,在该线程中按照时间流逝来删除vec_1中的元素, 同时每次的while 循环用getline(cin,yes_no)来结束该次生成的线程,在下一次循环中再生成新的线程来处理删除操作,但是在后台窗口中每次都是第一次while循环把vec_1中的元素删光后才能cin. 是我的写法有问题还是窗口模式下不能实现多线程?
...全文
165 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

15,471

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC 进程/线程/DLL
社区管理员
  • 进程/线程/DLL社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧