Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > C/C++: Программирование под Unix/Linux > Pthread tigger


Автор: UserNet 16.8.2010, 20:15
Народ есть программа у которой 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;
}


Автор: boostcoder 16.8.2010, 20:21
Цитата(UserNet @  16.8.2010,  20:15 Найти цитируемый пост)
1)Правильно ли реальзованы mutex в этой программе, для доступа двух потоков к одному массиву?

да.

Цитата(UserNet @  16.8.2010,  20:15 Найти цитируемый пост)
2)Как сделать триггер для потока?

что имеется в виду?

Автор: UserNet 16.8.2010, 20:24
Про триггер имется ввиду следующие:
Произошло добавление элемента в массив,то есть сработала функция insertarr(int value),
запустился третьи поток, вывел элементы массива на экран, иначе третьий поток ожидает.

Автор: djamshud 16.8.2010, 20:27
UserNet, 2 - use semaphore, Luke.

Автор: boostcoder 16.8.2010, 20:33
Цитата(UserNet @  16.8.2010,  20:24 Найти цитируемый пост)
Произошло добавление элемента в массив,то есть сработала функция insertarr(int value),
запустился третьи поток, вывел элементы массива на экран, иначе третьий поток ожидает. 

это: https://computing.llnl.gov/tutorials/pthreads/#ConditionVariables

Автор: UserNet 16.8.2010, 21:48
Попробовал переписать по примеру, поток который выводит на экран работает только один раз.
Код

#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;
pthread_cond_t    view =  PTHREAD_COND_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_cond_signal(&view);
    pthread_mutex_unlock(&insert_mutex);    
    sleep(1);
    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("view thread");
    pthread_mutex_lock(&insert_mutex);
    pthread_cond_wait(&view, &insert_mutex);
    printf("\narray = ");
    for (i = 0; i < 2 * n; i++) {
    
        printf("%i ",arr[i]);
    }

    printf("\n");
    pthread_mutex_unlock(&insert_mutex);
    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_mutex_init(&insert_mutex, NULL);
    pthread_cond_init (&view, NULL);
    
    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;
}

Автор: boostcoder 16.8.2010, 22:35
так:
Код

#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;
pthread_cond_t    view =  PTHREAD_COND_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_cond_signal(&view);
    pthread_mutex_unlock(&insert_mutex);    
    sleep(1);
    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) {
   while (1) { /* придумай способ завершения цикла */
      int        i;
      printf("view thread");
      pthread_mutex_lock(&insert_mutex);
      pthread_cond_wait(&view, &insert_mutex);
      printf("\narray = ");
      for (i = 0; i < 2 * n; i++) {

         printf("%i ",arr[i]);
      }
      printf("\n");
      pthread_mutex_unlock(&insert_mutex);
   }
   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_mutex_init(&insert_mutex, NULL);
    pthread_cond_init (&view, NULL);
    
    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;
}


Автор: UserNet 16.8.2010, 22:44
Спасибо.

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)