0

私は複数のスレッドを作成し、食事の哲学者の問題のために各スレッドに異なる値を渡そうとしています。しかし、私はこのエラーが発生しています:

warning: cast to pointer from integer of different size  

これが私のコードです:

pthread_mutex_t mutex;
pthread_cond_t cond_var;
pthread_t philo[NUM];

int main( void )
{
    int i;
    pthread_mutex_init (&mutex, NULL);
    pthread_cond_init (&cond_var, NULL);

    //Create a thread for each philosopher
    for (i = 0; i < NUM; i++)
        pthread_create (&philo[i], NULL,(void *)philosopher,(void *)i);  // <-- error here

    //Wait for the threads to exit
    for (i = 0; i < NUM; i++)
        pthread_join (philo[i], NULL);

    return 0;
}

void *philosopher (void *num)
{
    //some code
}
4

1 に答える 1

0

この警告は単にint、すべてのプラットフォームで an がポインターと同じサイズであるとは限らないことを意味します。警告を回避するにはiintptr_t. Anintptr_t ポインタと同じサイズであることが保証されています。しかし、別の解決策を提案させてください。

次のコードは、一意の情報を各スレッドに渡しながら、複数のスレッドを開始する方法を示しています。手順は次のとおりです。

  1. スレッドごとに 1 つのエントリを持つ配列を宣言する
  2. 各スレッドの配列エントリを初期化します
  3. 配列エントリをスレッドに渡します
  4. スレッドの開始時に配列から情報を取得する

以下のサンプル コードでは、各スレッドに 1 つの整数を渡したいので、配列は単なるint. スレッドごとにより多くの情報が必要な場合は、 の配列を持つことが適切structです。

コードは 5 つのスレッドを開始します。各スレッドには一意の ID ( int0 ~ 4) が渡され、少し遅れてコンソールに表示されます。遅延の目的は、スレッドの開始時期に関係なく、スレッドがそれぞれ一意の ID を取得することを示すことです。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <pthread.h>

#define NUM 5
static int infoArray[NUM];    // 1. declare an array with one entry for each thread

void *philosopher( void *arg );

int main( void )
{
    int i; 
    pthread_t threadID[NUM]; 

    srand( time(NULL) );

    for ( i = 0; i < NUM; i++ )
    {
        infoArray[i] = i;     // 2. initialize the array entry for this thread

        // 3. pass the array entry to the thread
        if ( pthread_create( &threadID[i], NULL, philosopher, (void *)&infoArray[i] ) != 0 )  
        {
            printf( "Bad pthread_create\n" );
            exit( 1 );
        }
    }

    for ( i = 0; i < NUM; i++ )
        pthread_join( threadID[i], NULL );

    return( 0 );
}

void *philosopher( void *arg )
{
    sleep( rand() % 3 );

    int id = *(int *)arg;   // 4. retrieve the information from the array
    printf( "%d\n", id );

    return( NULL );
}
于 2014-11-21T04:08:33.597 に答える