2017-11-21 4 views
0

私はpthreadsに新しいことを理解しようとしています。私はもう1つのスレッドを作成する新しいスレッドを作成するプログラムを作成しました...そして、threads_count!= 10まで続きます。私は配列として2つのパラメータをスレッドに渡したいと思う。私がメインから呼び出すと、それが動作します。関数の中で関数を呼び出すと、私は何かのようになります配列ポインタはスレッドでどのように機能しますか?

Sleeping for 4 sec before thread creation 
Sleeping for 32767 sec before thread creation 
Sleeping for 28762 sec before thread creation 
Sleeping for 28762 sec before thread creation 
Sleeping for 28762 sec before thread creation 
Sleeping for 28762 sec before thread creation 

私は関数の引数を新しいスレッドに間違って渡していますか? (それはすでにポインターだとして)あなただけの最後の引数としてthread_argsを使用する必要がありますしているときに、二重のポインタを渡しているSpanTwoThreads()内部pthread_create(&t1, NULL, SpawnTwoThreads, &thread_args);

#include <stdio.h> 
#include <pthread.h> 
#include <stdlib.h> 
#define MAX_THREADS 10 

int threads_count = 0; 



void* SpawnTwoThreads(void *args) { 
    pthread_t t1; 
    pthread_t t2; 

    int* thread_args = (int*)args; 
    printf("Sleeping for %d sec before thread creation\n", thread_args[1]); 
    sleep(5); 
    if(threads_count < MAX_THREADS) { 
     threads_count++; 
     thread_args[1] = rand() % 10; 
     pthread_create(&t1, NULL, SpawnTwoThreads, &thread_args); 
    } 
    pthread_exit(NULL); 
} 

int main(void) { 
    pthread_t t1; 
    int t1_wait_time; 

    srand(time(NULL)); 

    int start_args[2]; 
    start_args[0] = 0; 
    start_args[1] = rand() % 10; 
    pthread_create(&t1, NULL, SpawnTwoThreads, &start_args); 

    printf("In main: waiting for all threads to complete\n"); 
    pthread_join(t1, NULL); 
    printf("Overall waittime is %d\n", wait_time_overall); 
    pthread_exit(NULL); 
} 
+0

ローカル変数へのポインタを渡していますが、関数が戻るときに無効になります。 – Barmar

+0

グローバル変数にするとセグメント化エラーになる –

+1

すべての 'thread_args'は' main() 'から来た同じポインタのコピーなので、毎回' start_args [1] 'を上書きします。 'threads_count'のインクリメントの周りにもmutexを使うべきです。 – Barmar

答えて

1

main()関数では、start_argsが配列として宣言されているため、この問題は発生しません。そのため、配列の前に&シンボルを置くことは、配列自体の名前と同じになります。

関連する問題