Skip to content

Instantly share code, notes, and snippets.

@jbdrvl
Created April 15, 2018 18:51
Show Gist options
  • Select an option

  • Save jbdrvl/cac72604b4ffe55ea3443daf098d265b to your computer and use it in GitHub Desktop.

Select an option

Save jbdrvl/cac72604b4ffe55ea3443daf098d265b to your computer and use it in GitHub Desktop.
simple threads presentation in C
all : threads
threads : test-threads.c
gcc -lpthread test-threads.c -o threads
run : threads
./threads
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
int X=0, Y=0;
int Xdef=0,Ydef=0;
pthread_mutex_t lock;
void* display_entry(){
/* affiche la position toutes les secondes */
for (int i=0; i<5; i++){
/* debut SC1 */
pthread_mutex_lock(&lock);
printf("x,y = %d,%d\n",Xdef,Ydef);
pthread_mutex_unlock(&lock);
/* fin SC1 */
sleep(1);
}
return NULL;
}
int main(){
pthread_t display;
pthread_create(&display,NULL,display_entry,NULL);
/* update de la position
potentiellement complexe et asynchrone,
donc X et Y sont passées dans Xdef et Ydef qu'une fois le travail fini */
sleep(1);
X+=10;
printf("[INFO] just changed x to 10\n");
sleep(2);
Y+=10;
printf("[INFO] just changed y to 10\n");
/* debut SC2 */
printf("[INFO] locking display\n");
pthread_mutex_lock(&lock);
printf("[INFO] changing Xdef and Ydef\n");
Xdef=X;
Ydef=Y;
printf("[INFO] unlocking display\n");
pthread_mutex_unlock(&lock);
/* fin SC2 */
pthread_join(display,NULL);
pthread_mutex_destroy(&lock);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment