我有两个线程一和二。由它们各自在头文件中的类定义。我想在第一个线程启动时启动第二个线程。在第一个的构造函数中创建和启动第二个线程产生了意外的结果。我的头文件“header.h”
#ifndef HEADER
#define HEADER
#include <QtGui>
class One:public QThread
{
public:
One();
void run();
};
class Two:public QThread
{
public:
Two();
void run();
};
#endif
我的类文件“main.cpp”
#include "header.h"
#include<iostream>
using namespace std;
One::One()
{
/* the output just hangs at thread two and does not get to thread one run */
Two b;
b.start();
b.wait();
}
void One::run()
{
cout<<"One run\n";
int i=0;
for(;;)
{
i++;
cout<<"+++ "<<i<<endl;
if(i==10)
break;
sleep(3);
}
}
Two::Two()
{
}
void Two::run()
{
cout<<"Two run\n";
int i=0;
for(;;)
{
i--;
cout<<"----- "<<i<<endl;
sleep(3);
}
}
int main(int argc,char* argv[])
{
One a;
// Two b;
a.start();
// b.start();
a.wait();
// b.wait();
return(0);
}
这是我期望输出如何运行的工作代码。
编辑:更改了代码,以便现在两个线程都正确独立
我如何启动第二个线程和第一个线程,而不在 main ie 中显式调用两个。
int main(int argc,char* argv[])
{
One a;
Two b;
a.start();
b.start();
a.wait();
b.wait();
return(0);
}
线程二的调用和处理应该由线程一来完成。