switchbrew / switch-examples

Switch examples for devkitA64 and libnx.

Home Page:https://devkitpro.org/viewforum.php?f=42

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Threading examples

T4cC0re opened this issue · 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.

commented

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.

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

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.

commented
    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.

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?