cocos2d notification/event/message from a different thread - multithreading

I have a worker thread doing calculation on the background and I want to send a event/message to call a update function to update the graphics on screen once the worker thread finish calculation.
How do I do that in cocos2d ?
Some demo code:
-(void) updateGraphic
{
//this one update all the graphics/sprite
}
//note workerThreadFunc is being used to start a new thread
-(void) workerThreadFunc
{
//...
//...
//finish calculation here
//since it's in a different thread, I cannot call updateGraphic directly here
//So I need a event to notify update Graphic here somehow
}

Cocos2D calls the -(void) draw {} method on all nodes automatically on the main thread. You do not need to call that method from another thread, and you can not perform custom OpenGL drawing outside the draw method.
In order to call a method that should be performed on the main thread, use the performSelectorOnMainThread method.

I've achieve it via pthreads, it needs to do some changes in CCDirector.cpp & CCDirector.h
the details is in this thread.
to use it, we can register handleMessageInUI in UI thread, then worker thread sends a message to UI thread, which will call handleMessageInUI to do UI drawing. some sample code is below:
In UI thread, we can register a handler to process message in UI thread.
bool HelloWorldScene::handleMessageInUIThread(const EXTCCMessage &msg) {
// implementations
// return true if this handler has processed this msg,
// otherwise, false is returned
switch (msg.msgId) {
case 2:
break;
default:
return false;
}
return true;
}
// register this Handler to UI Threader
CCDirector::mainLoopHandler()->registerHandler(this, (EXTCCHandleMessage)&HelloWorldScene::handleMessageInUIThread);
send a message to UI thread in a worker thread
EXTCCMessage msg;
msg.msgId = 2;
msg.msgData1 = NULL;
// "msg" will be processed by "handleMessageInUIThread" in UI thread
CCDirector::mainLoopHandler()->postMessage(msg);

Related

Glib & Gstreamer: Does a probe callback behave like another thread in glib

I am trying to ask a question with reference to the question Glib: Calling a iterative loop function
I am actually doing GStreamer and trying to use Glib library function in my application as much as possible. The program require some system event/response before performing some action in response to some user input
Design of flow
User input the option and application take it as user_input is asserted to be true
Application need install a callback (called it callback_A) -- which wait out for buffer flowing in that point of application
Callback-A will be called whenever buffer passes through a point.
In callback A, Application to wait for some particular condition (ie a key-frame buffer passing through) at a point. If a key frame buffer pass through, it will then install a second callback at some point downstream, callback-B. An EOS event is send out through the pipeline. Otherwise wait for next time a buffer pass through
In callback B, it will wait for the event (EOS) to arrive and determine further action. If everything is completed, set task_completed to be true
function return to main while loop. The blocking (task_completed) is released and the application will report the task completed to UI
Problem'
Currently I faced a problem of the callback not completing their task (takes a long time) before it went to being blocked by task completed (and being blocked thereafter)
Question
In Glib, is a callback within the same memory space(or thread) as its caller?
In Glib, how do I overcome the problem of being blocked? Is there some methods to ensure that the task are being run before time up and control is returned to the caller
Will a gthread help? Putting the two call-back as a separate thread since they need to wait for some events to happen
This may be too much. Any alternatives, example polling instead of callback in this case.
Code
Here is my pseudocode
gbool user_input;
gbool task_completed = false;
static void
callback_B(GstPad *pad,
GstPadProbeInfo *info,
gpointer udata)
{
//// wait for some events--- call it event B
GstEvent *event = GST_PAD_PROBE_INFO_EVENT (info);
if (GST_EVENT_TYPE (event) != GST_EVENT_EOS)
return GST_PAD_PROBE_OK;
/// do something
/// ......
task_completed =true;
return GST_PAD_PROBE_REMOVE;
}
static void
callback_A( GstPad *pad,
GstBuffer * buffer,
gpointer udata)
{
//// wait for some event call it event A
if( !GST_BUFFER_FLAG_IS_SET(buffer, GST_BUFFER_FLAG_DELTA_UNIT))
{
/// install callback-B to determine some condition
gst_pad_add_probe ( pad,
GST_PAD_PROBE_TYPE_BLOCK,
(GSourceFunc)callback_B,
//NULL,
NULL,
NULL);
GstPad* padB = gst_pad_get_peer (pad);
gst_pad_send_event(padB, gst_event_new_eos());
}
else
{
return GST_PAD_PROBE_REMOVE;
}
}
gboolean
check_cmd_session(NULL )
{
if(user_input)
{
// ........ some other actions *****************
/// initialize task_complete to be false
task_completed = false;
//// install callback_A
gst_pad_add_probe(padA,
GST_PAD_PROBE_TYPE_BUFFER,
callback_A,
NULL,
NULL);
while(!task_completed)
g_usleep(10000);
/// notify UI of changes done
notify_UI();
}
}

Access the main OMNET++ simulation thread from a working/child thread

I wrote a simple multi-threaded application in OMNET++ that does not call any OMNET++ API in the working thread and is working as expected. I know that OMNET++ does not support multi-thread applications by design, but I was wondering if there is any mechanism that I can use to make a bridge between my worker thread and my code in the main simulation thread.
More specifically, I am saving some data in a vector in the working thread and I want to signal the code in the simulation thread to consume it (producer/consumer scenario). Is there any way to achieve this?
Do I need to design my own event scheduler?
METHOD 1
The simplest way to achieve your goal is to use a selfmessage in simulation thread and a small modification of worker thread. The worker thread should modify a common variable (visible by both threads). And the selfmessage should periodically check the state of this variable.
The sample code of this idea:
// common variable
bool vectorReady;
// worker thread
if (someCondition) {
vectorReady = true;
}
// simulation thread
void someclass::handleMessage(cMessage * msg) {
if (msg->isSelfMessage()) {
if (vectorReady) {
vectorReady = false;
// reads vector data
}
scheduleAt(simTime() + somePeriod, msg);
}
The place of declaration of common variable depends how you create and start the worker thread.
METHOD 2
The other way is to create own scheduler and adding a condition just before every event. By default OMNeT++ uses cSequentialScheduler scheduler. It has the method takeNextEvent() which is called to obtain next event. You can create a derived class and overwrite this method, for example:
// cThreadScheduler.h
#include <omnetpp.h>
using namespace omnetpp;
class cThreadScheduler : public cSequentialScheduler {
public:
virtual cEvent *takeNextEvent() override;
};
// cThreadScheduler.cc
#include "cThreadScheduler.h"
Register_Class(cThreadScheduler);
cEvent* cThreadScheduler::takeNextEvent() {
if (vectorReady) {
vectorReady = false;
// reads vector data
}
return cSequentialScheduler::takeNextEvent();
}
In omnetpp.ini add a line:
scheduler-class = "cThreadScheduler"

Updating a cocoa interface while processing code in a separate thread, using performSelectorInBackground

I am writing an app that can revert the firmware of a particular device. While executing this revert code, I wish to display a progress indicator.
This problem is of course best tackled with the use of multiple threads (http://stackoverflow.com/questions/1225700/can-i-start-a-thread-by-pressing-a-button-in-a-cocoa-interface-and-keep-using-in).
I have implemented the performSelectorInBackground method, which (according to the documentation) launches the specified selector in a separate thread. Meanwhile, my GUI is updated from the main thread by querying the 'reverter' object.
However, the GUI does not seem to be updating until the code in the secondary thread has finished executing. I obviously need the two to run in parallel. Here is what I've got so far - I'd be really grateful for any help as this is my first time with threading.
-(IBAction)pushButton:(id)sender{
//instatiate reverter object, which does all the firmware processing
Reverter *reverter = [[Reverter alloc] init];
//update the GUI to show a tab with a progress indicator
[tabView selectTabViewItemWithIdentifier:#"RevertProgressTab"];
//process revert code in a separate thread
[reverter performSelectorInBackground:#selector(revertFirmware) withObject:nil];
//process is complete when reverter progress reaches 100
while (!([reverter progress] == 100)) {
//check for failure
if ([reverter hasFailed]) {
[self showRevertFailureTab:nil];
return;
}
//update the progress indicator in the interface
[revertProgressBar setDoubleValue:(double)[reverter progress]];
[NSThread sleepForTimeInterval:0.05];
}
[self showRevertSuccessTab:nil];
}
Have I done anything obvious that would stop the GUI from being updated while the revertFirmware method runs?
Your while loop
while (/*condition*/) {
[NSThread sleepForTimeInterval:x];
}
will prevent your UI from updating. Your UI will only update as soon as your pushButton: method returns.
Instead of polling I would advice you start using an asynchronous event model:
Add a delegate to your reverter object
#protocol ReverterDelegate <NSObject>
- (void) reverterProgressDidUpdate:(float)progress;
#end
#interface Reverter : NSObject {
id<ReverterDelegate> delegate;
}
#property(assign) id<ReverterDelegate> delegate;
#end
Register your controller class as a delegate to your reverter
reverter.delegate = self;
and handle that event
- (void) reverterProgressDidUpdate:(float)progress {
// update ui
}
In your background thread send out events to the main thread
- (void) revertFirmware {
// once in a while send notifications of progress updates
if ([self.delegate respondsToSelector:#selector(reverterProgressDidUpdate:)]) {
[self.delegate performSelectorOnMainThread:#selector(reverterProgressDidUpdate:) withObject:[NSNumber numerWithFloat:progress] waitUntilDone:NO];
}
}
Make sure you retain your reverter somewhere, and release it when it's done working. You are now leaking in your pushButton: method. Also this is just a suggestion towards a better model. Instead of using performSelectorInBackground you could take a look at NSOperation and NSOperationQueue for example.

What's the good way to synchronize calls to a NSView?

I have a view that receives new data from a secondary thread. Every time it does, it should redraw itself. However, it doesn't play nice with the run loop, and after some time (it's non-deterministic), I end up getting <Error>: kCGErrorIllegalArgument: CGSUnionRegionWithRect : Invalid region messages in the console.
I'm not sure what's the right way to synchronize the calls to [view setNeedsDisplay:YES] across threads; can you help me?
To clarify a little, thread B (actually a dispatch queue) gives new contents to a view by calling this:
-(void)setImageBuffer:(unsigned char*)buffer
{
/* image handling stuff; thread-safe */
[self setNeedsDisplay:YES]; // but this is not thread-safe
}
And then thread A, on which runs the run loop, should redisplay the view.
-(void)setImageBuffer:(unsigned char*)buffer
{
/* image handling stuff; thread-safe */
[self performSelectorOnMainThread:#selector(induceRedraw)
withObject:nil
// Don't just copy this; pick one...
waitUntilDone:YES or NO];
}
-(void)induceRedraw
{
[self setNeedsDisplay:YES]; // but this is not thread-safe
}
With GCD you don't need the extra proxy method:
dispatch_queue_t q = dispatch_get_main_queue();
dispatch_async(q, ^(void) {
[self setNeedsDisplay: YES];
});

Problem in suspending 2 threads at the same time in MFC!

I am learning about threading and multithreading..so i just created a small application in which i will update
the progressbar and a static text using threading.I vl get two inputs from the user, start and end values
for how long the loop should rotate.I have 2threads in my application.
Thread1- to update the progressbar(according to the loop) the static text which will show the count(loop count).
Thread2 - to update the another static text which will just diplay a name
Basically if the user clicks start, the progressbar steps up and at the same time filecount and the name are displayed parallely.
There's is another operation where if the user clicks pause it(thread) has to suspend until the user clicks resume.
The problem is,the above will not work(will not suspend and resume) for both thread..but works for a singlw thread.
Please check the code to get an idea and reply me what can done!
on button click start
void CThreadingEx3Dlg::OnBnClickedStart()
{
m_ProgressBar.SetRange(start,end);
myThread1 = AfxBeginThread((AFX_THREADPROC)MyThreadFunction1,this);
myThread2 = AfxBeginThread((AFX_THREADPROC)MyThreadFunction2,this);
}
thread1
UINT MyThreadFunction1(LPARAM lparam)
{
CThreadingEx3Dlg* pthis = (CThreadingEx3Dlg*)lparam;
for(int intvalue =pthis->start;intvalue<=pthis->end; ++intvalue)
{
pthis->SendMessage(WM_MY_THREAD_MESSAGE1,intvalue);
}
return 0;
}
thread1 function
LRESULT CThreadingEx3Dlg::OnThreadMessage1(WPARAM wparam,LPARAM lparam)
{
int nProgress= (int)wparam;
m_ProgressBar.SetPos(nProgress);
CString strStatus;
strStatus.Format(L"Thread1:Processing item: %d", nProgress);
m_Static.SetWindowText(strStatus);
Sleep(100);
return 0;
}
thread2
UINT MyThreadFunction2(LPARAM lparam)
{
CThreadingEx3Dlg* pthis = (CThreadingEx3Dlg*)lparam;
for(int i =pthis->start;i<=pthis->end;i++)
{
pthis->SendMessage(WM_MY_THREAD_MESSAGE2,i);
}
return 0;
}
thread2 function
LRESULT CThreadingEx3Dlg::OnThreadMessage2(WPARAM wparam,LPARAM lparam)
{
m_Static1.GetDlgItem(IDC_STATIC6);
m_Static1.SetWindowTextW(L"Thread2 Running");
Sleep(100);
m_Static1.SetWindowTextW(L"");
Sleep(100);
return TRUE;
}
void CThreadingEx3Dlg::OnBnClickedPause()
{
// TODO: Add your control notification handler code here
if(!m_Track)
{
m_Track = TRUE;
GetDlgItem(IDCANCEL)->SetWindowTextW(L"Resume");
myThread1->SuspendThread();
WaitForSingleObject(myThread1->m_hThread,INFINITE);
myThread2->SuspendThread();
m_Static.SetWindowTextW(L"Paused..");
}
else
{
m_Track = FALSE;
GetDlgItem(IDCANCEL)->SetWindowTextW(L"Pause");
myThread1->ResumeThread();
myThread2->ResumeThread();
/*myEventHandler.SetEvent();
WaitForSingleObject(myThread1->m_hThread,INFINITE);*/
}
}
I thought I should summarize some of the discussion in the comments into an answer.
In Windows programming, you should never try to manipulate a GUI control from a background thread, as doing so can cause your program to deadlock . This means only the main thread should ever touch elements of the GUI. (Technically, what matters is which thread created the control, but it's not common to create controls in background threads).
This requirement is detailed in Joe Newcomer's article on worker threads (see "Worker Threads and the GUI II: Don't Touch the GUI").
You are using SendMessage in your thread procedures. This causes the appropriate message handler for the target control to be invoked, but in the thread that called SendMessage. In your case, that means the background threads run the message handlers and therefore update the progress bar and label.
The alternative is to use PostMessage. This causes the message to be added to a queue to be processed by the main thread's message loop. When the main thread gets to run, it processes the messages in the order they were added to the queue, calling the message handlers itself. Since the main thread owns the windows, it is safe for it to update the controls.
You should also beware that SuspendThread and ResumeThread are tricky to get right. You might want to read this section of Joe Newcomer's article, which describes some of the dangers.
Tasks like this are often better achieved by using a timer. This is a mechanism for having the operating system notify your program when a particular amount of time has passed. You could implement this with a timer as below:
BEGIN_MESSAGE_MAP(CThreadingEx3Dlg, CDialog)
ON_WM_DESTROY()
ON_WM_TIMER()
END_MESSAGE_MAP()
void CThreadingEx3Dlg::OnTimer(UINT_PTR nTimerID)
{
static int progress = 0;
if (nTimerID == 1)
{
m_ProgressBar.SetPos(progress);
CString strStatus;
strStatus.Format(_T("Processing item: %d"), progress);
m_Static.SetWindowText(strStatus);
progress++;
if (progress > end) // If we've reached the end of the updates.
KillTimer(1);
}
}
BOOL CThreadingEx3Dlg::OnInitDialog()
{
// ... initialize controls, etc, as necessary.
SetTimer(1, 100, 0);
}
void CThreadingEx3Dlg::OnDestroy()
{
KillTimer(1);
}
If you want both updates handled at the same time, they can use the same timer. If they need to happen at different times (such as one at a 100 ms interval and another at a 150 ms interval) then you can call SetTimer twice with different IDs. To pause the action, call KillTimer. To resume it, call SetTimer again.
Multi-threading and message queuing is quite a complex game. When you SendMessage from ThreadA to the same thread then it just calls the message handler. If you do it from ThreadA to another thread (ThreadB) then it gets more complicated. ThreadA then posts a message to the ThreadB's message queue and waits on a signal to say that ThreadB has finished processing the message and sent the return value. This raises an instant problem. If ThreadB is not pumping messages then you have a deadlock as the message in ThreadB's will never get "dispatched". This also raises an EVEN bigger problem. If ThreadB's message needs to send a message to a control created in ThreadA then you have a massive architectural problem. As ThreadA is currently suspended waiting for ThreadB to return and ThreadB is suspended waiting for ThreadA to return. Nothing will happen ... They will both sit suspended.
Thats about it really. Its pretty easy as long as you bear these issues in mind. ie It absoloutely IS possible despite what the others have said.
In general though your threading is pretty pointless because you straight away send a message to the main thread to do some processing. Why bother starting the threads in the first place. You may as well not bother because the threads will just sit there waiting for the main thread to return.
Why do you "WaitForSingleObject" anyway when you suspend the first thread? Why not just suspend them both.
All round, though, you aren't giving enough information about what you are doing to say exactly whats going on. What happens when you click pause, for example?
Windows will not operate properly when more than one thread interacts with the GUI. You'll need to reorganize your program so that does not happen.

Resources