从线程到主程序的反馈 [英] Feedback from threads to main program

查看:107
本文介绍了从线程到主程序的反馈的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的软件将模拟数百个硬件设备,每个设备将向数据库服务器发送数千个报告.

My software will simulate a few hundred hardware devices, each of which will send several thousand reports to a database server.

在没有线程的情况下尝试并没有得到很好的结果,因此现在是该线程的时候了.

Trying it without threading did not give very good results, so now it's time to thread.

由于我正在对d/b服务器进行负载测试,因此其中一些事务将成功,而一些事务可能会失败.主程序的GUI需要反映这一点.线程应如何将其结果传递回主程序?更新全局变量?发送消息?还是有什么不好的?

Since I am load testing the d/b server, some of those transactions will succeed and a few may fail. The GUI of the main program needs to reflect this. How should the threads communicate their results back to the main program? Update global variables? Send a message? Or something lese?

现在,如果我仅在每个线程的末尾进行更新,则GUI看起来会很无聊(而且我无法确定程序是否挂起).定期更新GUI可能会很好.但这可能导致争用,线程等待其他线程更新(例如,如果我正在写全局变量,则需要一个互斥体,该互斥体将阻塞每个正在等待写的线程).

Now, if I update only at the end of each thread then the GUI is going to look rather boring (and I can't tell if the program hung). It might be nice to update the GUI periodically. But that might cause contention, with threads waiting for other threads to update (for instance, if I am writing to global variables, I need a mutex, which will block each thread which is waiting to write).

我是线程处理的新手.通常如何做?也许主程序可以轮询线程,而不是构成主程序的线程?

I'm new to threading. How is this normally done? Perhaps the main program could poll the threads, instead of the threads iforming the main program?

推荐答案

组织此方法的一种方法是让您的线程将消息添加到线程安全队列中(例如,

One way to organize this is for your threads to add messages to a thread-safe queue (e.g. a ConcurrentQueue) as they get data. To keep things simple you can have a timer thread in your UI that periodically dequeues the queued messages to a private list and then renders them. This design allows your threads to easily queue and forget messages with minimal contention, and for your UI to periodically update itself without blocking your writers too much (i.e. for only the period it takes to dequeue current messages to a private list).

尽管您试图模拟数百个设备的负载,但是使用每个设备的线程并不是建模的方法,因为无论如何您只能同时运行这么多线程.

Although you are attempting to simulate the load of hundreds of devices, using thread per device is not the way to model this as you can only run so many threads concurrently anyway.

这篇关于从线程到主程序的反馈的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆