pthread & С

Модератор: Модераторы разделов

Ответить
Serega955
Сообщения: 35

pthread & С

Сообщение Serega955 »

С института не писал на С, но сегодня я выдавил из себя такой код:
Предполагается что в самом дампе только инсерты.

Код: Выделить всё

#include <my_global.h>
#include <mysql.h>
#include <pthread.h>

int thread_count;

struct thread_template {
   char str_buffer[4096];
   int   id;
};

typedef struct {
   char str_buffer[4096];
   int   id;
} thread_template;


int main()
{
  char host[10]="localhost";
  char user[10]="root";
  char passwd[10]="";
  char file_name[10]="dump.sql";

  int thread_max=10;

  FILE *fp;
  char next_str[4096];

  int status;

  //multi thread init
  if (mysql_library_init(0, NULL, NULL)) {
    fprintf(stderr, "could not initialize MySQL library\n");
    exit(1);
  }

  //void *thread_run(void *thread_id){
  void *thread_run(void* arg){
    sleep(1);
    thread_template* new=(thread_template*)arg;
    printf("##THREAD ID: %i\n",new->id);
    //printf("##THREAD EXECUTE: %s\n",new->str_buffer);
    printf("##THREAD COUNT: %i\n",thread_count);

    MYSQL *con = mysql_init(NULL);
    if (con == NULL){
       fprintf(stderr, "%s\n", mysql_error(con));
       exit(1);
    }


    if (mysql_real_connect(con, host, user, passwd, "eld", 0, NULL, 0) == NULL){
       fprintf(stderr, "%s\n", mysql_error(con));
        mysql_close(con);
        exit(1);
    }

    if (mysql_query(con, new->str_buffer)){
      fprintf(stderr, "%s\n", mysql_error(con));
      mysql_close(con);
      exit(1);
     }else{
    printf("##THREAD ID: %i\n",new->id);
    printf("##THREAD EXECUTE: %s\n",new->str_buffer);
    printf("##THREAD COUNT: %i\n",thread_count);
     }

    if (thread_count>0) thread_count--;
    mysql_thread_end();
    pthread_exit(NULL);
    return NULL;
  }

  pthread_t tid;
  fp = fopen(file_name , "r");

  if(fp == NULL) {
   perror("Error opening file");
   return(-1);  }

  struct thread_template new[10];

   while(1){
        if(thread_count==thread_max){
        printf("SLEEP...\n");
        sleep(1);
    }else{
                while(fgets(next_str, sizeof(next_str), fp) && thread_count<thread_max){
            printf("@@@@@ ARBITR SAY: parse string: %s",next_str);
              thread_count++;
               new[thread_count].id=thread_count;
              strcpy(new[thread_count].str_buffer, next_str);
                  pthread_create( &tid, NULL, thread_run,&new[thread_count] );
            pthread_join(tid, NULL);                                       /*тут проблема*/
         }
         }
   }

  //mysql_close(con);
  mysql_library_end();
  exit(0);
}


Все работает, но есть проблема (строка pthread_join(tid, NULL); )
Без этой строки, по понятным причинам, некоторые треды не успевают доработать, а с этой строкой, код начинает выполняться строго последовательно. Помогите понять, как исправить данную проблему.
Спасибо сказали:
Аватара пользователя
/dev/random
Администратор
Сообщения: 5282
ОС: Gentoo

Re: pthread & С

Сообщение /dev/random »

Сохраняйте все tid'ы в массив и вызывайте pthread_join только после того, как все потоки запущены, в отдельном цикле.


iУведомление от модератора /dev/random
Перемещено из "Программ" в "Программирование"

Спасибо сказали:
IMB
Сообщения: 2559
ОС: Debian

Re: pthread & С

Сообщение IMB »

Уберите вызов pthread_join из цикла, да и зачем он Вам если Вы не сохраняете код выхода потока.
Я бы использовал pthread_detach и в программе ожидал некого сигнала/признака, что все потоки завершили работу.
Спасибо сказали:
Serega955
Сообщения: 35

Re: pthread & С

Сообщение Serega955 »

Спасибо за ответы. Все ясно, все получилось.
Спасибо сказали:
Ответить