Tell an existing thread to do something Ruby - ruby

I'm playing a bit with event machine, and got some code that run on another thread, I want his callback to get synced back to the main thread, so I'd like to do something like this:
thread.post { fiber.resume(result) }
The fiber parent is thread but context of execution is on another thread.
thanks,

Found it
EventMachine.schedule
does the trick

Related

Can I assign my own "thread names" in Xcode?

Xcode's "thread list" pane shows English-like names for several special threads: com.apple.main-thread, com.apple.libdispatch-manager, com.dispatchfractal.opencl, com.dispatchfractal.opengl, com.apple.root.low-priority,... But for user-created threads that field is just blank.
Is there any way to set that "thread name" field programmatically from my application? For example, if I've got a thread devoted to network I/O, I'd like it to show up as "com.example.network-io" in the debugger; if I spawn five worker threads I'd like to be able to name them "worker A", "worker B", etc. Does Xcode pull its thread-names from some API that I could hook into myself? Maybe something like CFAssignDebuggerNameToCurrentThread? :)
Probably not exactly what you want but NSThread has setName: method that allows you to set thread's name, you can attach meaningful name to the thread so you'll get the following in debugger:
[[NSThread mainThread] setName:#"That is main thread!"];
Remember also that some apis (like grand central dispatch) operate with thread pools so you are not guaranteed on what thread your operation will be performed
Edit:
com.apple.main-thread, com.apple.libdispatch-manager etc are labels of corresponding dispatch queues. You can set label value when queue is created with dispatch_queue_create function and later get it from the queue using dispatch_queue_get_label function.
It seems there's no API to change label value of the existing dispatch queue and I would not advise to change labels of the system queues anyway.
If you can get a reference to the thread whose name you want to change, you can change it in the debugger console. Two ways to do that for the current thread:
(lldb) po [[NSThread currentThread] setName:#"foo"]
(lldb) expression (void)[(NSThread*)[NSThread currentThread] setName:#"foo"];
I'd guess you could do the same from a breakpoint that has an associated expression. If you have a method that you know will run in the thread that you're interested in, you could set a breakpoint containing one of the above commands and have it automatically continue after running the command. That'd have the effect of automatically setting the name of the thread every time you run the code, which might be handy for debugging.
I use the following code in Swift 5 to rename the current thread:
pthread_setname_np("myThreadName")
pesudo code for -[NSThread setName:]
- (void) setName:(NSString*)thname {
if (self == [NSThread currentThread])
{
pthread_setname_np([thname UTF8String]);
}
else { ... }
...
}
So, the easist way to set name is calling pthread_setname_np.

Troubles trying to start two asynchronous tasks.

I want to start two Async Tasks but the second will not start until the first has completed.
From what I've googled, people usually suggest this approach:
new MyAsyncTask().execute(params);
new MyAsyncTask().execute(params);
However, I need to instantiate them separately and also keep the handles of the task's (to pass messages for example). Therefore, I SORT OF do this:
onStart()
{
taskA = new MyAsyncTask(paramsA);
taskB = new MyAsyncTask(paramsB);
}
onButtonPress()
{
taskA.execute();
taskB.execute();
}
Edit:
I've noticed that taskB does not actually start executing until taskA completes (which runs a tcp/ip server so it takes a long time). I cannot figure out why. Any thoughts or comments ?
The short answer is that, depending on your version of Android, all AsyncTask subclasses may be using the same thread, so you can only do one at a time. There are two ways around this:
Use Runnable instead of AsyncTask
Replace one call to execute with executeOnExecutor(Executor.THREAD_POOL_EXECUTOR, params)
Clearly, try #2 first - it's less of a code change. But if that doesn't work pretty quickly, I'd switch to #1. In that case, you don't have to worry about how Android might change in the future.
If you want more details about the threading model for AsyncTask, have a look at the Android doc entry.

Using `event_generate` when tkinter runs in a new thread

I need to generate virtual events for a tkinter window running in a separate thread. Calling event_generate from non-gui thread is supposed to be safe and it works well, when tkinter runs in the main thread and events are generated in another thread.
For a certain reason I need that the statements generating the events run in main thread (more specifically, I want those statements to be in the toplevel of the module).
But, when I do root = Tk(); root.mainloop() in a new thread and root.event_generate("<<my-event>>") in the main thread, I get stack overflow. When I swap the threads (root = Tk(); root.mainloop() in the main thread and root.event_generate("<<my-event>>") in a new thread) then everything works again.
I have taken care that root is fully construted (and also idle), before I try generating the event.
Any ideas how to get this setup working?
(I'm using Python 3.2.3)
Found the answer myself: put only root.mainloop() in secondary thread, keep root = Tk() in main thread.

Problem wuth Ruby threads

I write a simple bot using "SimpleMUCClient". But got error: app.rb:73:in stop': deadlock detected (fatal)
from app.rb:73:in'. How to fix it?
Most likely the code you're running is executed in another thread. That particular thread is then joined (meaning Ruby waits for it to finish upon exiting the script) using Thread.join(). Calling Thread.stop() while also calling .join() is most likely the cause of the deadlock. Having said that you should following the guides of StackOverflow regarding how to ask questions properly, since you haven't done so I've down voted your question.
Joining a thread while still calling Thread.stop can be done as following:
th = Thread.new do
Thread.stop
end
if th.status === 'sleep'
th.run
else
th.join
end
It's not the cleanest way but it works. Also, if you want to actually terminate a thread you'll have to call Thread.exit instead.

Windows Forms: thread safe access to GUI?

in the last hours I've struggled with delegates and accessing Windows Forms controls (C++) where I've used this tutorial (the first thread safe method): http://msdn.microsoft.com/en-us/library/ms171728.aspx#Y190
Changing TextBoxes and Labels works perfectly but when I want to show or hide the whole GUI from another thread this fails.
I use the following methode (which is part of the GUI class):
System::Void UI::showUI(boolean value) {
if (this->InvokeRequired) {
SetTextDelegate^ d = gcnew SetTextDelegate(this, &UI::showUI);
this->Invoke(d, gcnew array<Object^> { value });
} else {
if (value == true)
this->Show();
else
this->Hide();
}
}
In the first call the if-clause is true so Invoke is called. But usually the showUI method should be called a second time automatically where the if-clause returns false, but this is not happening. So the GUI is neither shown nor hiden.
Is it necessary to show/hide the GUI with a delegate or can I do it from every possible thread? If a delegate is necessary, why is showUI not executed a second time?
Thanks,
Martin
edit: okay the name SetTextDelegate is not appropriate but this is not the point...
This is a pretty standard case of deadlock, not uncommon with Control::Invoke(). It can only proceed if the UI thread is not busy. Use Debug + Windows + Threads and double-click the Main thread. Look at the call stack to see what it is doing. The typical case is that it is blocking, waiting for the thread to finish the job. That will never happen since the thread can't complete until the Invoke() call returns.
Don't block the UI thread.
Consider using BackgroundWorker, its RunworkerCompleted event is nice to do stuff after the thread completes, removing the need to block.

Resources