Java和C++/Qt中线程的差异
<> P> java版本工作完全符合预期,C++版本崩溃。C++版本在1和lt==时工作。N_线程<;=2.否则它就失败了 我努力奋斗了几个小时,试图使C++版本工作,但失败了,仍然不知道发生了什么。当然,我会通过研究系统线程和Qthread源代码来了解这个问题,是的,我会尝试这样做,但我现在确实需要一个解决方案感谢您的帮助
螺纹试验。爪哇
class my_thread extends Thread
{
int n;
my_thread()
{
n = 0;
}
public void run()
{
try
{
while (n < 10)
{
System.out.print(n++);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
return;
}
}
}
public class thread_test
{
public static void main(String[] args)
{
final int N_THREADS = 10;
for (int i = 0; i < N_THREADS; i++)
{
new my_thread().start();
}
}
}
螺纹试验。cpp
#include <array>
#include <QTextStream>
#include <QThread>
QTextStream qout(stdout);
class my_thread : public QThread
{
public:
int n;
my_thread()
{
n = 0;
}
void run()
{
while(n < 10)
{
qout << n++ << flush;
msleep(1000);
}
}
};
int main()
{
enum { N_THREADS = 10 };
std::array<my_thread, N_THREADS> thread_array;
for (auto& thread : thread_array)
{
thread.start();
}
for (auto& thread : thread_array)
{
thread.wait();
}
return 0;
}
编辑
阅读谷歌的评论和一些搜索,我的C++代码中的问题显然是在多线程中使用非线程安全操作。所以在这里,我的问题将通过使QTextStream像Java的PrintStream一样线程安全来解决基于我的快速网络搜索,我猜QTextStream与标准输出交互的过程不应该通过多个线程同时完成,因为只有一个标准输出。但在一个线程与标准输出交互期间,让所有其他线程等待的速度太慢。因此,我认为正确的解决方案应该是在stdout繁忙且无法同时接受更多任务时,创建一个队列来存储要写入的输出,作为QString引用。那么,在这里我如何保证这个队列是线程安全的呢?我现在很困惑。另外,Java PrintStream是如何实现线程安全的?请帮助我组织这些问题,并找到正确的解决方案
# 1 楼答案
在
Qt
中,你不应该派生QThread
,因为你想要的是functionality run in a thread
,而不是thread having that functionality
看看这些链接,第一个描述了更一般的线程,第二个帮助实现
https://www.qt.io/blog/2010/06/17/youre-doing-it-wrong
what is the correct way to implement a QThread... (example please...)