47 lines
887 B
C
47 lines
887 B
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <pthread.h>
|
|
#include <unistd.h>
|
|
|
|
#define max 6
|
|
|
|
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
|
|
|
|
|
|
void unlock(){
|
|
pthread_mutex_unlock(& mutex);
|
|
}
|
|
|
|
|
|
void * fn_thread (void * n) {
|
|
pthread_mutex_lock(& mutex);
|
|
printf("[THREAD] J'ai le mutex.\n");
|
|
|
|
for (int i = 0; i < max; ++i){
|
|
printf("[THREAD] tid: %ld\n", pthread_self());
|
|
sleep(1);
|
|
}
|
|
|
|
pthread_mutex_unlock(& mutex);
|
|
|
|
pthread_exit(0);
|
|
}
|
|
|
|
|
|
int main () {
|
|
pthread_t p1;
|
|
|
|
for (int i = 0; i < 2; ++i){
|
|
pthread_create (& p1, NULL, fn_thread, NULL);
|
|
pthread_cleanup_push( &unlock, NULL );
|
|
|
|
for (int i = 0; i < max/2; ++i){
|
|
printf("[MAIN] pid: %d\n", getpid());
|
|
sleep(1);
|
|
}
|
|
pthread_cancel(p1);
|
|
pthread_cleanup_pop(1);
|
|
sleep(1);
|
|
}
|
|
return 0;
|
|
}
|