switch-examples icon indicating copy to clipboard operation
switch-examples copied to clipboard

Threading examples

Open T4cC0re opened this issue 5 years ago • 5 comments

Hey there!

I would like to request some examples of a multi-threaded application. Specifically one, that does background tasks and then joins the threads later.

I tried to do this with both libNX threads and std::thread but I cannot get the threads to work reliably (i.e. not freeze the app at random times). I cannot easily post my code without massive modifications, so I would like to take a look at a reference implementation to see what I am doing wrong.

T4cC0re avatar Aug 28 '19 11:08 T4cC0re

Standard threading APIs (i.e. pthreads, C threads, C++ threads) are all supported on the Switch (except for detach-type functionality which is not), so you can refer to any reputable programming resource that shows you how to use those. Everything should work fine; if there's something that doesn't then please let us see a test case in which it fails.

fincs avatar Aug 28 '19 11:08 fincs

Okay, I'll try to port some code, that does not reliably work for me, so we can figure out why that is.

T4cC0re avatar Aug 28 '19 11:08 T4cC0re

I uploaded a repo with sample code and instructions here https://github.com/T4cC0re/libnx-threads-freeze

It would be great if you could take a look. Most of the time it just works, but sometimes it freezes after creating a thread. That might be a bug in libnx? I don't know. It also seems to be dependant on app start. Because a restart of the same code may either work or freeze.

T4cC0re avatar Sep 02 '19 14:09 T4cC0re

    int i = 0;
    // Make the thread busy
    while (i < 10000) {
        i++;
    }
    return i * threadNr;

This will do nothing, as the compiler will optimize it out since the loop does nothing (it will turn it into just return 10000 * threadNr). Use volatile int to prevent this. Plus, this number of iterations is too low.

fincs avatar Sep 02 '19 14:09 fincs

Hey @fincs Thanks for taking a look. I just pushed an update, that makes reproduction a bit easier. I also added a linux target to sanity check my code. And the weird thing is, that on Linux it works flawless. So there has to be something funky in HorizonOS, libnx or the switch hardware...

So I am guessing this is not the right place and this should rather be a libnx issue?

T4cC0re avatar Sep 04 '19 17:09 T4cC0re