threads.c
00001 #include <pthread.h>
00002 #include <stdio.h>
00003 #include <unistd.h>
00004
00005
00006 #define NB_THREADS_FILS 4
00007
00008 pthread_mutex_t verrou;
00009
00010 void *unthread(void* x) {
00011 int i, *n = x;
00012 for (i = 0; i < 10; i++) {
00013 pthread_mutex_lock(&verrou);
00014 fprintf(stderr, "Thread %d au rapport: itération n°%d\n", *n, i);
00015 pthread_mutex_unlock(&verrou);
00016 #ifndef PTH_YIELD_UNDEF
00017 pthread_yield();
00018 #endif
00019 }
00020 pthread_exit(NULL);
00021 }
00022
00023 int main()
00024 {
00025 pthread_t threads[NB_THREADS_FILS];
00026 int i, nums[NB_THREADS_FILS] = {0};
00027 pthread_mutex_init(&verrou, NULL);
00028
00029 for (i = 0; i < NB_THREADS_FILS; i++) {
00030 nums[i] = i;
00031 pthread_create(&threads[i], NULL, unthread, &nums[i]);
00032 }
00033
00034 for (i = 0; i < 10; i++) {
00035 if (i == 3) pthread_mutex_lock (&verrou);
00036 if (i == 7) pthread_mutex_unlock(&verrou);
00037 fprintf(stderr, "Thread \"père\" au rapport: itération n°%d\n", i);
00038 #ifndef PTH_YIELD_UNDEF
00039 pthread_yield();
00040 #endif
00041 }
00042
00043 for (i = 0; i < NB_THREADS_FILS; i++)
00044 pthread_join(threads[i], NULL);
00045 pthread_mutex_destroy(&verrou);
00046 return 0;
00047 }