最近在模擬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. 是我的寫法有問題還是視窗模式下不能實作多執行緒?
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/16918.html
標籤:進程/線程/DLL
上一篇:求助,PING批處理腳本問題
下一篇:vc2010除錯成功但運行不出來
