How to pass a fiber to a thread? - multithreading

I am wondering how I do I pass a fiber to a thread?
The only way that I managed to do it was by casting to and from shared.
auto fiber = new Fiber((){
});
auto t = spawn((){
auto fib = cast(Fiber)receiveOnly!(shared(Fiber));
writeln("fib");
fib.call();
});
send(t, cast(shared(Fiber))fiber);
But that doesn't seem right. I think I don't fully understand the implications of shared.
I had to cast the fiber to shared because I wasn't allowed to send it to the thread without it. I had to cast it back to a fiber because I couldn't call Fiber.call on a shared fiber.
What is the correct way of passing a Fiber to a thread?

There is no support for moving fibres across threads, right now (and probably will never be). Using shared could somehow works, but it is dangerous, and I am not sure if it will work ok with all compilers. Some more info is in this dlang forum thread:
http://forum.dlang.org/post/m2r3prh3ki.fsf#comcast.net

Related

MSAA not in the main thread produce new behavior

I have an issue with Microsoft Active Accessibility and threads in Qt. Code for example below:
CComPtr<IAccessible> _pAccMain;
HWND _hWnd = ...; // Handle of some window
HRESULT hr0 = ::AccessibleObjectFromWindow(_hWnd,
OBJID_CLIENT,
IID_IAccessible,
(void**)(&_pAccMain));
long childCount = 0;
HRESULT hr1 = _pAccMain->get_accChildCount(&childCount);
It works fine and in the main-thread these functions returns success for hr0 and hr1 and I got a proper success data for _pAccMain and childCount. But when I create a new thread and try to use the code in that new thread I got again success for hr0 and hr1, but I got different data in _pAccMain and childCount. I.e. the same code have more than one behavior in different threads.
Why another thread have another behavior in that example?
How can I fix it behavior?
Can I fix it?
There is no promise that AccessibleObjectFromWindow calls return the same interface pointer, so _pAccMain values don't have to be pointer-equal
Additionally, calling from different threads (apartments) might have marshaling involved, in which case you might get a proxy interface, not real object interface; it is behavior by design that those are different pointers
By mentioning different childCount you should have mentioned if worker thread get you zero, or otherwise what exactly is different in child enumeration
There is no free COM pointer passing between threads in COM, what your question suggests you are doing; you can only do this with MTA threads, and otherwise you have to marshal/unmarshal pointers to get a valid pointer in another thread
It seems like Qt quietly initialized COM in each new thread and after that CoInitializeEx with any COINIT can't do anything with it. But if you call in new QThread CoUnitialize before CoInitializeEx all will be ok, it is works for me.

winapi apc function parameter passing - what is the best practice

Hi i using winapi's QueueUserAPC to invoke an apc function call in another thread.
my question is, what is the best practice for passing a parameter to it.
i refer to the object lifetime and allocation/deallocation responsibility.
DWORD WINAPI QueueUserAPC(PAPCFUNC pfnAPC, HANDLE hThread, ULONG_PTR dwData);
i am using the dwData to pass the parameter to pass a pointer to some data and i was wondering how i should handle it.
i need to make sure that it lives until the receiving thread finished using it.
should i use a smart pointer to make sure that data is deallocated when no longer used?
i guess that allocation in the calling thread and dealloc. in the receiving is possible but probably not such a good thing.
anything else that can be done?
i think i would like to avoid synchronization between the two only to notify that the receiving thread is done with the data...
thanks!
Alloc'ing in the sending thread and dealloc'ing in the receiving one is easy, but it has the main drawback that it may leak, even if you handle the sending failure, the receiving thread may finish before having a chance to execute the APC.
Probably your easiest way to avoid the leak is to create a queue for sent data -maybe a queue per thread- and when thread finishes, you traverse the thread queue and free all the pending data.
But as usual, the devil is in the details...

Multithreading (pthreads)

I'm working on a project where I need to make a program run on multiple threads. However, I'm running into a bit of an issue.
In my program, I have an accessory function called 'func_call'.
If I use this in my code:
func_call((void*) &my_pixels);
The program runs fine.
However, if I try to create a thread, and then run the function on that, the program runs into a segmentation fault.
pthread_t thread;
pthread_create (&thread, NULL, (void*)&func_call, (void*) &my_pixels);
I've included pthread.h in my program. Any ideas what might be wrong?
You are not handling data in a thread safe manner:
the thread copies data from the thread argument, which is a pointer to the main thread's my_pixels variable; the main thread may exit, making my_pixles invalid.
the thread uses scene, main thread calls free_scene() on it, which I imagine makes it invalid
the thread calls printf(), the main thread closes stdout (kind of unusual itself)
the thread updates the picture array, the main thread accesses picture to output data from it
It looks like you should just wait for the thread to finish its work after creating it - call pthread_join() to do that.
For a single thread, that would seem to be pointless (you've just turned a multi-threaded program into a single threaded program). But on the basis of code that's commented out, it looks like you're planning to start up several threads that work on chunks of the data. So, when you get to the point of trying that again, make sure you join all the threads you start. As long as the threads don't modify the same data, it'll work. Note that you'll need to use separate my_pixels instances for each thread (make an array of them, just like you did with pthreads), or some threads will likely get parameters that are intended for a different thread.
Without knowing what func_call does, it is difficult to give you an answer. Nevertheless, here are few possibilities
Does func_call use some sort of a global state - check if that is initialized properly from within the thread. The order of execution of threads is not always the same for every execution
Not knowing your operating system (AIX /Linux/Solaris etc) it is difficult to answer this, but please check your compilation options
Please provide the signal trapped and atleast a few lines of the stack-trace - for all the threads. One thing you can check for yourself is to print the threads' stack-track (using threads/thread or pthread and thread current <x> based on the debugger) and and if there is a common data that is being accessed. It is most likely that the segfault occurred when two threads were trying to read off the other's (uncommitted) change
Hope that helps.
Edit:
After checking your code, I think the problem is the global picture array. You seem to be modifying that in the thread function without any guards. You loop using px and py and all the threads will have the same px and py and will try to write into the picture array at the same time. Please try to modify your code to prevent multiple threads from stepping on each other's data modifications.
Is func_call a function, or a function pointer? If it's a function pointer, there is your problem: you took the address of a function pointer and then cast it.
People are guessing because you've provided only a fraction of the program, which mentions names like func_call with no declaration in scope.
Your compiler must be giving you diagnostics about this program, because you're passing a (void *) expression to a function pointer parameter.
Define your thread function in a way that is compatible with pthread_create, and then just call it without any casts.

QPointer in multi-threaded programs

According to http://doc.qt.io/qt-5/qpointer.html, QPointer is very useful. But I found it could be inefficient in the following context:
If I want to show label for three times or do something else, I have to use
if(label) label->show1();
if(label) label->show2();
if(label) label->show3();
instead of
if(label) { label->show1();label->show2();label->show3(); }
just because label might be destroyed in another thread after label->show1(); or label->show2();.
Is there a beautiful way other than three ifs to get the same functionality?
Another question is, when label is destroyed after if(label), is if(label) label->show1(); still wrong?
I don't have experience in multi-threaded programs. Any help is appreciated. ;)
I think the only safe way to do it is to make sure you only access your QWidgets from within the main/GUI thread (that is, the thread that is running Qt's event loop, inside QApplication::exec()).
If you have code that is running within a different thread, and that code wants the QLabels to be shown/hidden/whatever, then that code needs to create a QEvent object (or a subclass thereof) and call qApp->postEvent() to send that object to the main thread. Then when the Qt event loop picks up and handles that QEvent in the main thread, that is the point at which your code can safely do things to the QLabels.
Alternatively (and perhaps more simply), your thread's code could emit a cross-thread signal (as described here) and let Qt handle the event-posting internally. That might be better for your purpose.
Neither of your approaches is thread-safe. It's possible that your first thread will execute the if statement, then the other thread will delete your label, and then you will be inside of your if statement and crash.
Qt provides a number of thread synchronization constructs, you'll probably want to start with QMutex and learn more about thread-safety before you continue working on this program.
Using a mutex would make your function would look something like this:
mutex.lock();
label1->show();
label2->show();
label3->show();
mutex.unlock()
As long as your other thread is using locking that same mutex object then it will prevented from deleting your labels while you're showing them.

Getting a reference to the current boost::thread/interrupting the main thread

I am trying to get a reference to the main boost::thread of execution, so that I can interrupt it.
However, boost::thread doesn't seem to supply any way of doing this.
I have searched on the internet but I can't seem to find an answer to this question.
I did see some old answers, but they seem to be relevant to old boost code.
The closest one said that using boost::thread t; (the default constructor) will give me a reference to the current thread. However, the boost documentation seems to say that that will create a reference to a not-a-thread.
My main goal is to interrupt the main thread, and not get a reference to the current boost::thread, but that seemed like the easiest way.
My current solution is to create a new thread from main, and just join() it. Is there any way to get the current thread object (or interrupt it) and not use this workaround?
Thanks
A default constructed boost::thread object used to (in v1.34 and earlier) refer to the current thread, but it does not do so any longer.
You cannot interrupt the main thread in boost. Your workaround of starting a new thread to do the work, and joining it from main() is the best way.

Resources