Народ есть программа у которой 3 потока, два потока добавляют элементы в массив, а третьий поток в случае добавления элемента, выводи массив на экран. Два вопроса 1)Правильно ли реальзованы mutex в этой программе, для доступа двух потоков к одному массиву? 2)Как сделать триггер для потока?
| Код | #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <semaphore.h> #include <time.h>
int n = 12, *arr; pthread_mutex_t insert_mutex = PTHREAD_MUTEX_INITIALIZER; int insertarr(int value) { int i , num; pthread_mutex_lock(&insert_mutex); for (i = 0; i < 2 * n; i++) { if (arr[i] == -1) { num = i; break; } } arr[num] = value; pthread_mutex_unlock(&insert_mutex); return 0; }
void * thread_proc_one(void *data) { int i , tmp; for (i = 0; i < n; i++) { tmp = rand() % 100; printf("id1 value = %i \n", tmp); insertarr(tmp); }
return NULL; }
void * thread_proc_two(void *data) { int i , tmp; for (i = 0; i < n; i++) { tmp = rand() % 100; printf("id2 value = %i \n", tmp); insertarr(tmp); } return NULL; } void * thread_proc_thr(void *data) { int i; printf("\narray = "); for (i = 0; i < 2 * n; i++) { printf("%i ",arr[i]); }
printf("\n"); return NULL; }
int main(int argc, char *argv[]) { int i; pthread_t thread_one, thread_two, thread_thr; srand(time(NULL)); arr = calloc(24, sizeof(int)); for (i = 0; i < 2 * n; i++) arr[i] = -1; pthread_create(&thread_one, NULL, &thread_proc_one, NULL); pthread_create(&thread_two, NULL, &thread_proc_two, NULL); pthread_create(&thread_thr, NULL, &thread_proc_thr, NULL); pthread_join(thread_one, NULL); pthread_join(thread_two, NULL); pthread_join(thread_thr, NULL); return 0; }
|
|