我有两个线程一和二。由它们各自的类在头文件中定义。我想在第一个线程启动时启动第二个线程。在第一个线程的构造函数中创建并启动第二个线程产生了意想不到的结果。 我的头文件 "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);
}
这是我期望输出如何运行的工作代码。
Edit: changed the code so that now both the threads are properly independent
How do i start the second thread along with the first thread, without explicitly calling two in main i.e .
int main(int argc,char* argv[])
{
One a;
Two b;
a.start();
b.start();
a.wait();
b.wait();
return(0);
}
The invoking and handling of thread two should be done by thread one..
最佳答案
我相信您可能误解了一些线程概念。听起来您想启动两个线程,然后从一个线程上下文调用另一个线程上下文的函数,这不是线程的工作方式。
当您启动这两个线程时,它们彼此独立执行。他们可以共享对数据的访问,但你不能按照你想要的方式交织他们的执行。如果你想让一个线程根据另一个线程的请求执行某事,你有两个决定两件事:
- 使用哪种机制将请求从一个线程发送到另一个线程
- 请求线程是应该停止并等待“接收”,还是在另一个线程执行它被要求的操作时愉快地继续。
一个非常的简单(而且不是很安全,这只是说明逻辑)机制是使用两个 bool 值来发出请求信号,例如:
Thread one starts | Thread two starts
Thread one works | Thread two loops checking a `bool DoSomething;`
Thread one sets bool DoSomething |
Thread one loops waiting for DidSomething | Thread two beeps
| Thread two sets DidSomething
Thread one continues working |
需要注意的是线程上下文之间没有“调用”。两个线程同时执行,并通过数据(两个bool)进行通信。
在现实世界的多线程中,您不得不担心同时访问数据。例如什么会如果两个线程同时在双核机器上尝试将数据附加到同一个列表,就会发生这种情况。两个线程可能会看到相同的“列表结束指针”,都将创建一个新条目,都将更新“列表结束指针”。但是其中一个更改会覆盖另一个,在最好的情况下你会丢失一些数据和内存泄漏,在最坏的情况下你会崩溃。
这就是你使用“互斥”机制的地方:每个线程在访问像列表这样的共享资源之前,都会获得一个互斥量。互斥锁的构造方式是一次只有一个线程可以“拥有”它。如果线程 1 碰巧先获得了互斥量,它将继续进行列表更新,然后释放互斥量。与此同时,其他尝试获取互斥量的线程将简单地坐在那里,Mutex::acquire() 调用将不会返回,直到第一个线程完成互斥量。如果两个线程都表现得很好,并且在访问共享列表之前获取了互斥量,则不会发生上述同时更新,并且在两个线程都更新后列表将完全有效。
回应评论:
您不能同时启动两个线程。最接近的近似是从 One::run 中创建并启动 Two:
void One::run()
{
Two b;
b.start();
cout<<"One run\n";
int i=0;
for(;;)
{
i++;
cout<<"+++ "<<i<<endl;
if(i==10)
break;
sleep(3);
}
b.wait();
}
关于c++ qthread同时启动2个线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5230444/