【发布时间】:2016-08-16 15:23:49
【问题描述】:
我通过函数Start_zeroMQResponderThread向我使用Qt开发的应用程序添加了一个新线程:
// this function adds the new thread
void MainWindow::Start_zeroMQResponderThread()
{
moveToThread(&zeroMQResponderthread);
QObject::connect(&zeroMQResponderthread, SIGNAL(started()), this, SLOT(Run_zeroMQResponderThread())); //cant have parameter sorry, when using connect
zeroMQResponderthread.start();
}
我在 MainWindow 的构造函数中调用了这个函数,以确保线程是在应用程序启动时创建的:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
....
// This is the sender which do not need to be run in a separate thread
context = zmq_ctx_new();
requester = zmq_socket(context, ZMQ_PAIR);
rc = zmq_connect(requester, "tcp://10.131.7.97:5555");
...
// This is the starting of the thread that will listens to the network to
// capture received messages using ZeroMQ
Start_zeroMQResponderThread();
}
最后,这是函数Run_zeroMQResponderThread():它在单独的线程中运行。它启动一个无限循环以使用 ZeroMQ 检测发送的消息,并使用 Windows Text To Speech API (SAPI) 将它们转换为语音消息:
void MainWindow::Run_zeroMQResponderThread() {
ISpVoice * pVoice = NULL;
if (!FAILED(::CoInitialize(NULL)))
{
HRESULT hr = CoCreateInstance(CLSID_SpVoice, NULL, CLSCTX_ALL, IID_ISpVoice, (void **)&pVoice);
}
void *context = zmq_ctx_new();
void *responder = zmq_socket(context, ZMQ_PAIR);
int rc = zmq_bind(responder, "tcp://*:5555");
printf("Receiver: Started\n");
char buffer[128];
wchar_t wtext[128];
while (true)
{
int num = zmq_recv(responder, buffer, 128, 0);
if (num > 0)
{
buffer[num] = '\0';
printf("Receiver: Received (%s)\n", buffer);
mbstowcs(wtext, buffer, strlen(buffer) + 1);//Plus null
LPWSTR ptr = wtext;
HRESULT hr;
if (pVoice)
hr = pVoice->Speak(ptr, SPF_DEFAULT, NULL);
if (!SUCCEEDED(hr))
std::cout << "speak error" << hr << std::endl;
}
}
pVoice->Release();
pVoice = NULL;
::CoUninitialize();
zmq_close(responder);
zmq_ctx_destroy(context);
}
在添加此功能之前,应用程序运行良好。但添加后它会在应用程序的开头冻结,甚至不显示应用程序的主 UI。
可能是什么问题?
【问题讨论】:
-
你为什么在你的
MainWindow上打电话给moveToThread?这将尝试将QWidget派生对象(MainWindow)移动到应用程序执行主线程以外的线程上。 Qt 通常不喜欢这样。我并不是说这绝对是问题所在,但它看起来确实很奇怪。 -
@G.M.并不是 Qt“一般”“不喜欢那样”。它不起作用,而且从来没有打算起作用。就是这样。
标签: c++ c multithreading qt zeromq