Hello - I am placing this here, as it seems the most appropriate place; please feel free to move this if it should be somewhere else!
I have come across a problem that I can't seem to figure out, and wonder if anyone would have any pointers?
I am writing some code in C++, using SDL2, and experimenting with threads. I have managed to make the problem reproducible in a fairly short piece of code, as follows (I will edit this if the code tags don't work!)
main.cpp:
<code>
#include <stdint.h>
#include <thread>
#include <SDL2/SDL.h>
#include "src/folder2/mylib.h"
void superloop_cplusplus();
int main( int argc, char* args[]){
if (SDL_Init(SDL_INIT_VIDEO)<0) {printf("init fail\n");} // print an error if fail
SDL_Surface* fbsurface = SDL_CreateRGBSurface(0, 800, 600, 32, 0xFF00, 0xFF0000, 0xFF000000, 0);
if (fbsurface == NULL) {printf("create surface fail\n");} // print an error if fail
mylibrary object; // create an object of type mylibrary
object.setvars(); // call a function to update some private vars
std::thread mythread_01(superloop_cplusplus); // call a very simple thread
printf("checking SDL_MUSTLOCK\n");
bool result = SDL_MUSTLOCK(fbsurface); // see if we need to lock our surface or not?
if (result == false) {printf("we don't need to lock this surface\n");}
printf("the check did not fail\n");
while (false == false) { // infinite loop
}
return 0;
}
void superloop_cplusplus()
{
while (false == false) {
// a thread that does an infinite loop
}
}
</code>
02 - the header file for the library
<code>
#ifndef HEADER_MYLIBRARY
#define HEADER_MYLIBRARY
class mylibrary{
public:
void setvars();
};
#endif
</code>
03 - the library itself
<code>
#include <stdint.h>
#include <string>
class mylibrary{
public:
void setvars();
private:
uint64_t var1;
uint64_t var2; // <-- writing to this one causes SDL2 to crash later on
uint64_t var3;
uint64_t var4;
};
void mylibrary::setvars(){
var1=1;
var2=1; // crashes SDL2
var3=1;
var4=1;
return;
}
</code>
(note - I am hoping that these code tags work, or that I can go back and edit / experiment to try to make them work)
(I did my best, but cannot change the default ‘wide spacing’)!
What I would hope would happen would be that I get some console output as follows:
checking SDL_MUSTLOCK
we don't need to lock this surface
** this may not appear if we do need to lock the surface
the check did not fail
What I actually get is :
checking SDL_MUSTLOCK
Hit any key to continue
(the program crashes, silently, hence this prompt)
if I comment out the ‘var2=1’ line in my library, then the check of SDL_MUSTLOCK works fine, but if I leave that line in place, then, for some reason, it does something that makes SDL crash later when doing SDL_MUSTLOCK
I am new to C++ (having only programmed in assembly for years), so I know there is a stupid mistake somewhere, and would be very grateful for any pointers, having spent hours on this so far!
Thank you for any advice 🙂