Hi
i am implementing a simple threaded GUI application in QT 4.6.2. I am using QThread without subclassing it. I have made a call to the usleep() function in my start() function this however results in freezing of the GUI. How do i get around this. Below is the code
#ifndef ECGREADER_H
#define ECGREADER_H
#include<QObject>
class ecgreader : public QObject
{
Q_OBJECT
public:
ecgreader(QObject *parent=0);
~ecgreader();
public Q_SLOTS:
void start();
Q_SIGNALS:
void finished();
};
#endif // ECGREADER_H
Below is the start() function
void ecgreader::start()
{
int i= system("ls>output.txt");
SLEEP(10000);
if(i==0)
{
emit finished();
}
}
finally the call to start is made here
void Application::onbtnclicked()
{
QThread* thread=new QThread;
ecgreader* reader=new ecgreader;
reader->moveToThread(thread);
connect(thread,SIGNAL(started()),reader,SLOT(start()));
connect(reader,SIGNAL(finished()),thread,SLOT(quit()));
connect(reader,SIGNAL(finished()),reader,SLOT(deleteLater()));
connect(reader,SIGNAL(finished()),thread,SLOT(deleteLater()));
reader->start();
}
Please help
You have two problems: first you created the thread, but you never started it. Second you are directly calling start() on your reader instead of emiting a signal.
I think what you meant was to call thread->start() instead of reader->start():
void Application::onbtnclicked()
{
QThread* thread=new QThread;
ecgreader* reader=new ecgreader;
reader->moveToThread(thread);
connect(thread,SIGNAL(started()),reader,SLOT(start()));
connect(reader,SIGNAL(finished()),thread,SLOT(quit()));
connect(reader,SIGNAL(finished()),reader,SLOT(deleteLater()));
connect(reader,SIGNAL(finished()),thread,SLOT(deleteLater()));
thread->start();
}
Related
I've written a simple DirectX11.2 app, which works. I wanted to add some cleanup code for when the app exits, however I noticed that my window does not actually handle closing, suspending, resuming or uninitializing properly.
According to the IFrameworkView documentation, Uninitialize() should get called before the application exits, but it never gets called (https://learn.microsoft.com/en-us/uwp/api/windows.applicationmodel.core.iframeworkview?view=winrt-19041)
I subscribe to the events that are supposed to fire when a window suspends, resumes, or closes, however it seems like none of those events ever actually fire.
I am under the impression that minimizing the window should suspend the application, clicking on the window from the task bar after it has been minimized should resume the application, and pressing the red X button in the top right corner of the window should close the application, am I wrong?
Here is the relevant code:
// the class definition for the core "framework" of our app
ref class App sealed: public IFrameworkView
{
bool m_windowClosed;
CGame m_game;
public:
// this function subscribes to suspend and resume events, and gets called properly
virtual void Initialize(CoreApplicationView^ appView) {
// set the OnActivated function to handle to Acivated "event"
appView->Activated += ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &App::OnActivated);
CoreApplication::Suspending += ref new EventHandler<SuspendingEventArgs^>(this, &App::Suspending);
CoreApplication::Resuming += ref new EventHandler<Object^>(this, &App::Resuming);
m_windowClosed = false;
}
// this function subscribes to the close() event. This function is called properly, but the Closed event never fires
virtual void SetWindow(CoreWindow^ window){
window->Closed += ref new TypedEventHandler<CoreWindow^, CoreWindowEventArgs^>(this, &App::Closed);
}
virtual void Load(String^ entryPoint) {}
virtual void Run() {
m_game.Initialize();
CoreWindow^ Window = CoreWindow::GetForCurrentThread();
// repeat until window closes
while (!m_windowClosed) {
// run processEvents() to dispatch events
// ProcessAllIfPresent makes ProcessEvents return once all events have been processed
Window->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent);
// run the rest of the game code here
m_game.Update();
m_game.Render();
}
// we never get here!
m_game.Finalize();
}
// never called, even though it should ALWAYS be called when the application exits?
virtual void Uninitialize() {
Log("Uninitialize()");
}
void OnActivated(CoreApplicationView^ coreAppView, IActivatedEventArgs^ args) {
CoreWindow^ window = CoreWindow::GetForCurrentThread();
window->Activate();
}
// never called
void Suspending(Object^ sender, SuspendingEventArgs^ args) {
Log("Suspending()");
}
// never called
void Resuming(Object^ sender, Object^ args) {
Log("Resuming()");
}
// never called
void Closed(CoreWindow^ sender, CoreWindowEventArgs^ args) {
m_windowClosed = true;
Log("Close()");
}
};
// the class definition that creates an instance of our core framework class
ref class AppSource sealed : IFrameworkViewSource {
public:
virtual IFrameworkView^ CreateView() {
// create an App class and return it
return ref new App();
}
};
[MTAThread] // define main() as a multi-threaded-apartment function
// the starting point of all programs
int main(Array<String^>^ args) {
// create and run a new AppSource class
CoreApplication::Run(ref new AppSource());
return 0;
}
Upon further research, I notice that Suspend and Resume are generally called when Windows itself suspends (sleep, hibernate) and resumes ("wakes up" from sleep or hibernate).
I have now found that the only event that's called before my app terminates is the CoreWindow::VisibilityChanged event.
Let's go straight to an example. Let's say we have:
Update(){
if (value.Equals("circular")) moveGameObjectInACircularWay();
else if (value.Equals("linear")) moveGameObjectInALinearWay();
}
I think that is not very elegant solution. Unity needs to perform a comparison every frame. That does not sound very optimal to me. I'm just guessing it should be some other way to implement the same like:
Start () {
if (value.Equals("circular")) movement += moveGameObjectInACircularWay;
else if (value.Equals("linear")) movement += moveGameObjectInALinearWay;
}
Update () {
movement();
}
I guess the solution is related with delegates. That's why my proposed solution looks like delegates. I don't understand what delegates are well yet.
From MSDN "A delegate in C# is similar to a function pointer in C or C++. Using a delegate allows the programmer to encapsulate a reference to a method inside a delegate object." (https://msdn.microsoft.com/en-us/library/aa288459(v=vs.71).aspx) In short is a pointer to a method. What you want to do is the following:
using UnityEngine;
using System.Collections;
public delegate void MovementDelegate();
public class Movement : MonoBehaviour {
MovementDelegate movementFunction=null;
public string value = "linear";
void Start () {
if (value.Equals("circular")) movementFunction = moveGameObjectInACircularWay;
else if (value.Equals("linear")) movementFunction = moveGameObjectInALinearWay;
}
// Update is called once per frame
void Update()
{
if (movementFunction != null)
{
movementFunction();
}
}
void moveGameObjectInACircularWay()
{
Debug.Log("do circular movement here");
}
void moveGameObjectInALinearWay()
{
Debug.Log("do linear movement here");
}
}
The functions you declare must have the same signature as the delegate signature. If you want to add parameters to it, ex. an int, decalre your delegate as
public delegate void MovementDelegate(int speed);
and your implementation functions as
void moveGameObjectInACircularWay(int speed)
void moveGameObjectInALinearWay(int speed)
and change the call to
movementFunction(yourIntHere)
UPDATED!: Thanks to Joe Blow suggestion here is another solution:
public class Movement : MonoBehaviour
{
Action<int> movementFunction = null;
public string value = "linear";
void Start()
{
if (value.Equals("circular")) movementFunction = moveGameObjectInACircularWay;
else if (value.Equals("linear")) movementFunction = moveGameObjectInALinearWay;
}
// Update is called once per frame
void Update()
{
if (movementFunction != null)
{
movementFunction(2);
}
}
void moveGameObjectInACircularWay(int speed)
{
Debug.Log("do circular movement here "+ speed);
}
void moveGameObjectInALinearWay(int speed)
{
Debug.Log("do linear movement here " + speed);
}
}
My favorite answer has been written by Joe Blow in the comments:
Unity is components based. We better switch to Component-Based Thinking instead working with delegates.
So make two (or more) different scripts, and put those on the game object in question. Then, turn on and off these components as you wish.
So we would have to scripts added to our game object: MoveGameObjectInACircularWay.cs and MoveGameObjectInALinearWay.cs. Then a MainGameObjectScript.cs also added to our game object with the following code:
void Start () {
GetComponent()<MoveGameObjectInACircularWay>.active = true;
GetComponent()<MoveGameObjectInALinearWay>.active = false;
}
I am working on a Pebble watch face and I ran into a problem, the function app_message_outbox_send seems to throw an error (which then crashes my app). The error is "[INFO ] E call_internal.c:36 syscall failure! 0..0x8 is not in app space."
The relevant code:
static void askPhoneForCharge(){
if(bluetooth_connection_service_peek()){
DictionaryIterator *iter;
app_message_outbox_begin(&iter);
dict_write_uint8(iter, KEY_PHONE_ASK, 0);
app_message_outbox_send();
}else{
phoneCharging = 0;
phoneCharge = 0;
updatePhoneBattery();
}
}
Here is how I set up the handlers and open the channel:
app_message_register_inbox_received(inboxReceivedCallback);
app_message_register_inbox_dropped(inboxDroppedCallback);
app_message_register_outbox_failed(outboxFailedCallback);
app_message_register_outbox_sent(outboxSentCallback);
app_message_open(app_message_inbox_size_maximum(), app_message_outbox_size_maximum());
As it turns out, you can not use the message functions while in the initialization phase, so I started a timer that only executes once to take care of the initial messaging.
I was having the same problem while sending the app_message_outbox_send() command which was getting called by to the Up_button_click handler.
The following initialization code in the Init() method fixed it for me.
Look at the "Register message handlers" & "Init buffers"
void out_sent_handler(DictionaryIterator *sent, void *context){}
static void out_fail_handler(DictionaryIterator *failed, AppMessageResult reason, void* context){}
static void in_received_handler(DictionaryIterator *iter, void* context){}
void in_drop_handler(AppMessageResult reason, void *context){}
static void init() {
// Register message handlers
app_message_register_outbox_sent(out_sent_handler);
app_message_register_inbox_received(in_received_handler);
app_message_register_inbox_dropped(in_drop_handler);
app_message_register_outbox_failed(out_fail_handler);
// Init buffers
app_message_open(64, 64);
// Create main Window element and assign to pointer
s_main_window = window_create();
// Set handlers to manage the elements inside the Window
window_set_window_handlers(s_main_window, (WindowHandlers) {
.load = main_window_load,
.unload = main_window_unload
});
// Show the Window on the watch, with animated=true
window_stack_push(s_main_window, true);
}
The following code is adapted from an example in Real-Time Java Platform Programming by Peter C. Dibble:
import javax.realtime.*;
public class OSTimer {
static volatile boolean cont = true;
public static void main(String[] args) {
AsyncEventHandler handler = new AsyncEventHandler(){
public void handleAsyncEvent() {
System.out.println("Stopping...");
cont = false;
}
}
};
OneShotTimer timer = new OneShotTimer(new RelativeTime(3000, 0), handler);
timer.start();
while(cont){
System.out.println("Running");
if (timer.isRunning()) System.out.println("Timer is running");
try {
Thread.sleep(1000);
} catch(Exception e) { }
}
System.exit(0);
}
The the program is supposed to run for 3 seconds and then exit. However, the output shows that while the timer did indeed stop after 3 seconds, the program continues as usual, i.e. output is:
Running
Timer is running
Running
Timer is running
Running
Timer is running
Running
Running
Running......
Clearly the handler did not fire, and I've no idea why. Another example program involving a periodic timer triggering the handler does work as expected. The program structure is almost the same as the one here.
A few things to try:
Call fire() explicitly on the timer instance to see if you can force things
Try creating your handler by passing in the logic as a Runnable object to the handler. The API is a little unclear on this, but this is how I have specified handlers in the past.
Example:
AsyncEventHandler handler = new AsyncEventHandler(new Runnable() {
public void run() {
System.out.println("Stopping...");
cont = false;
}
});
I am trying to create a class called InputManager to handle mouse events. This requires that mousePressed be contained within the InputManager class.
like so
class InputManager{
void mousePressed(){
print(hit);
}
}
problem is, that doesn't work. mousePressed() only seems to work when it's outside the class.
How can I get these functions nicely contained in a class?
Try this:
in main sketch:
InputManager im;
void setup() {
im = new InputManager(this);
registerMethod("mouseEvent", im);
}
in InputManager Class:
class InputManager {
void mousePressed(MouseEvent e) {
// mousepressed handling code here...
}
void mouseEvent(MouseEvent e) {
switch(e.getAction()) {
case (MouseEvent.PRESS) :
mousePressed();
break;
case (MouseEvent.CLICK) :
mouseClicked();
break;
// other mouse events cases here...
}
}
}
Once you registered InputManger mouseEvent in PApplet you don't need to call it and it will be called each loop at the end of draw().
Most certainly, but you are responsible for ensuring it gets called:
interface P5EventClass {
void mousePressed();
void mouseMoved();
// ...
}
class InputManager implements P5EventClass {
// we MUST implement mousePressed, and any other interface method
void mousePressed() {
// do things here
}
}
// we're going to hand off all events to things in this list
ArrayList<P5EventClass> eventlisteners = new ArrayList<P5EventClass>();
void setup() {
// bind at least one input manager, but maybe more later on.
eventlisteners.add(new InputManager());
}
void draw() {
// ...
}
void mousePressed() {
// instead of handling input globally, we let
// the event handling obejct(s) take care of it
for(P5EventClass p5ec: eventlisteners) {
p5ec.mousePressed();
}
}
I would personally make it a bit tighter by also passing the event variables explicitly, so "void mousePressed(int x, int y);" in the interface and then calling "p5ec.mousePressed(mouseX, mouseY);" in the sketch body, simply because relying on globals rather than local variables makes your code prone to concurrency bugs.
The easiest way to do so would be:
class InputManager{
void mousePressed(){
print(hit);
}
}
InputManager im = new InputManager();
void setup() {
// ...
}
void draw() {
// ...
}
void mousePressed() {
im.mousePressed();
}
This should solve any problems you were having with variable scoping in your class.
Note: In the class, it doesn't even have to be named mousePressed, you can name it anything you wish, as long as you call it inside of the main mousePressed method.