Skip to content

Instantly share code, notes, and snippets.

@DavidLudwig
Last active March 11, 2019 17:53
Show Gist options
  • Save DavidLudwig/69800375f0a06e3f9008197d2c816ede to your computer and use it in GitHub Desktop.
Save DavidLudwig/69800375f0a06e3f9008197d2c816ede to your computer and use it in GitHub Desktop.
//
// Compile with: em++ test-threads.cpp -o test-threads.html -s USE_PTHREADS=1 -s PTHREAD_POOL_SIZE=2 -s USE_SDL=2
//
// Expected behavior: program starts with a black screen, smoothly fades it to
// green, then resets (show black screen, fades-in green, rinse and repeat).
//
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <SDL.h>
#include <unistd.h>
#define GL_GLEXT_PROTOTYPES 1
#include <SDL_opengles2.h>
static pthread_t thread = 0;
static SDL_Window * window = 0;
static SDL_GLContext gl = 0;
void * thread_main(void *) {
while (true) {
if (SDL_GL_MakeCurrent(window, gl) < 0) {
printf("SDL_GL_MakeCurrent failed: %s\n", SDL_GetError());
} else {
GLfloat value = ((GLfloat)((SDL_GetTicks() / 25) % 255)) / 255.0f;
glClearColor(0, value, 0, 1);
glClear(GL_COLOR_BUFFER_BIT);
SDL_GL_SwapWindow(window);
}
// Commenting out the usleep(1000) call can cause Chrome to hang
usleep(1000); // sleep for 1ms (aka. 1000 us)
}
return 0;
}
int main() {
// Use OpenGL ES 2.0
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
// Init SDL
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS) != 0) {
printf("SDL_Init failed: %s\n", SDL_GetError());
return 1;
}
window = SDL_CreateWindow(
"Thread Test",
SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
640, 480,
SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE
);
if (!window) {
printf("SDL_CreateWindow failed: %s\n", SDL_GetError());
return 1;
}
gl = SDL_GL_CreateContext(window);
if (!gl) {
printf("SDL_GL_CreateContext failed: %s\n", SDL_GetError());
return 1;
}
// Spin off separate thread
if (pthread_create(&thread, NULL, thread_main, NULL) != 0) {
printf("pthread_create failed\n");
return 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment