2016-07-03 11 views
-1

まず私は、コードを投稿してみましょう:私が呼ぶときセグメンテーションフォールト

#include <pthread.h> 
#include<stdlib.h> 

//64 BITS -ALL 32 bit Arch 
//32 BIT - UNIX 64 bit arch 
//64 BIT - WINDOWS 64 bit arch 
long long sum = 0; 
static enum turn 
{ 
    PING, 
    PONG 
}def; 

struct threads_util 
{ 
    pthread_t *t_id; 
    pthread_attr_t *attr; 
    void (*init_attr)(pthread_attr_t *); 
}; 

void init_attr_fn(pthread_attr_t *attr) 
{ 
    pthread_attr_init(&attr); 
} 

void* sum_runner(void* arg) 
{ 
    long long* limit_ptr = (long long *) arg; 
    long long limit = *limit_ptr;//Derefrencing 
    for(long long i=0; i<=limit; i++) 
     sum += i; 
    printf("Sum is %lld \n", sum); 
    pthread_exit(0); 
} 

void ping() 
{ 
    puts("Ping"); 
    def = PONG; 
} 

void pong() 
{ 
    puts("Pong"); 
    def = PING; 
} 

pthread_t * all_thread(pthread_t *t_id) 
{ 
    t_id = malloc(sizeof(pthread_t)); 
    return t_id; 
} 

int main(int argc, char **argv) 
{ 
    if(argc<2) 
    { 
    puts("Usage ./objFile <num 1> <num 2> .. <num n>"); 
     exit(1); 
    } 

    int args = argc-1; 
    long long limit = atoll(argv[1]); 
    def = PING; 

    struct threads_util *threads[args]; 

    for (int i=0; i<args; i++) 
    threads[i]->t_id = all_thread(threads[i]->t_id); 
    puts("In");  
    for(int i=0; i<args; i++) 
    { 
     threads[i]->init_attr = init_attr_fn; 

     threads[i]->init_attr(threads[i]->attr); 
     pthread_create(threads[i]->t_id,threads[i]->attr,sum_runner,&limit); 
    } 

    //Begin -Main Functions 
    for(int i=0; i<= 10; i++) 
    { 
    if(def == PING) 
      ping(); 
     else if(def == PONG) 
      pong(); 
     else 
      puts("UNKOWN PI-PO");   
    } 
    //End - Main Functions 

    for(int i=0; i<args; i++) 
    { 
     pthread_join(threads[i]->t_id,NULL); 
    } 
} 

あなただけのforループの後、メイン機能では、私はプット(「中」)を持って見ることができますall_threadは時間をargsします。デバッグのスキルに合わせてforループを使って関数argcを呼び出すのは問題です。また、すべての割り当て戦略を実行する前に、スレッド関数を呼び出す際に問題が発生しましたが、もちろんSegmentation Faultが発生しました。 threads[i]->init_attr(threads[i]->attr);。ヘルプは非常に高く評価されるだろう。

答えて

0
struct threads_util *threads[args]; 

あなたはポインタstruct threads_utilからの配列を定義することを意味します。しかし、あなたが実際にどのstruct threads_utilので、この行を作成しないでください:

threads[i]->t_id = all_thread(threads[i]->t_id); 

が違法であることはない、割り当てられたメモリへの書き込みとして。

あなたが最初struct threads_utilにメモリを割り当てる必要があります。

for (int i=0; i<args; i++) 
    threads[i] = malloc(sizeof(struct threads_util)); 
+0

[OK]をイムは、その問題を渡す..あなたがチャットhttp://chat.stackoverflow.com/rooms/54304/cに行くことができますか?今、私は属性の初期化に問題があります:threads [i] - > init_attr(threads [i] - > attr); – amanuel2

+0

pthread_attr_init' – 4386427

+0

は 'スレッド[i]がようだ'は何ですか - > attr'が初期化されていない - 多分あなたはちょうど私がセグメンテーションフォールトモンスターを撃破しましNULL' – 4386427

関連する問題