Skip to content

Instantly share code, notes, and snippets.

@tonussi
Created May 7, 2013 03:02
Show Gist options
  • Save tonussi/5529994 to your computer and use it in GitHub Desktop.
Save tonussi/5529994 to your computer and use it in GitHub Desktop.
mutex.cpp
//http://www.libsdl.org/ install instructions tutorials
#include <SDL/SDL.h>
#include <SDL/SDL_thread.h>
#include <iostream>
#include <stdlib.h>
using namespace std;
bool quit = false, consumed = true;
int a = 0, b = 0;
SDL_mutex *mutex_a, *mutex_b; //Declares an SDL_mutex pointer, mutex_a and mutex_b:
int thread_a(void *data) {
char *thread_name = (char *) data;
while (!quit) {
//if thread_a reach inside while, begins action
printf("I am %s. \n", thread_name);
printf("I am %s. \n", &thread_name);
SDL_mutexP(mutex_a); //Lock the mutex_a before PROCESSING a
printf("%s has locked a\n", thread_name);
printf("%s has locked a\n", &thread_name);
++a; //instruction
SDL_Delay(10); //Wait 10 milliseconds before return
SDL_mutexP(mutex_b); //Lock the mutex_b before ACCESSING b
printf("%s has locked b\n", thread_name);
printf("%s has locked b\n", &thread_name);
a += b++;
SDL_mutexV(mutex_b); //Unlock the mutex_b
SDL_mutexV(mutex_a); //Unlock the mutex_a
SDL_Delay(rand() * 3000 + 1000); //Wait a period >= 1000
}
printf("%s quits\n", thread_name);
printf("%s quits\n", &thread_name);
return 0;
}
int thread_b(void *data) {
char *thread_name = (char *) data;
while (!quit) {
//if thread_b reach inside while, begins action
printf("I am %s. \n", thread_name);
printf("I am %s. \n", &thread_name);
SDL_mutexP(mutex_a); //Lock the mutex_a before PROCESSING a
printf("%s has locked a\n", thread_name);
printf("%s has locked a\n", &thread_name);
a += b; //instruction
SDL_mutexP(mutex_b); //Lock the mutex_b before ACCESSING b
printf("%s has locked b\n", thread_name);
printf("%s has locked b\n", &thread_name);
b++;
SDL_Delay(10); //Wait 10 milliseconds before return
SDL_mutexV(mutex_b); //Unlock the mutex_b
SDL_mutexV(mutex_a); //Unlock the mutex_a
SDL_Delay(rand() * 3000 + 2000); //Wait a period >= 2000
}
printf("%s quits\n", thread_name);
printf("%s quits\n", &thread_name);
return 0;
}
int main() {
cout << "Starting..." << endl; // prints Starting...
SDL_Thread *id_a, *id_b; //Thread's IDS
char *thread_name[2] = { "LOST_IN_SOUND", "PERSONA_FORMAX_SNIDER" }; //Thread's NAMES
mutex_a = SDL_CreateMutex();
mutex_b = SDL_CreateMutex();
//create the threads
id_a = SDL_CreateThread(thread_a, thread_name[0]);
id_b = SDL_CreateThread(thread_b, thread_name[1]);
//experiment with 20 seconds
for (int i = 0; i < 10; i++) {
SDL_Delay(2000);
}
quit = true; //signal the threads to return
//wait for the threads to exit
SDL_WaitThread(id_a, NULL);
SDL_WaitThread(id_b, NULL);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment