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

警告只是意味着 anint不一定与所有平台上的指针大小相同。为避免警告,您可以声明iintptr_t. An保证intptr_t 指针大小相同。但请允许我提出一个替代解决方案。

下面的代码演示了如何启动多个线程,同时将一条独特的信息传递给每个线程。步骤是

  1. 声明一个数组,每个线程都有一个条目
  2. 为每个线程初始化数组条目
  3. 将数组条目传递给线程
  4. 线程启动时从数组中检索信息

在下面的示例代码中,我们希望将一个整数传递给每个线程,因此该数组只是一个int. 如果每个线程需要更多信息,则最好有一个structs 数组。

代码启动五个线程。每个线程都会传递一个唯一的 ID(int介于 0 和 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 回答