【问题标题】:Passing information to multiple threads in the dining philosopher's algorithm将信息传递给餐饮哲学家算法中的多个线程
【发布时间】:2014-11-21 03:17:50
【问题描述】:

我正在尝试创建多个线程并将不同的值传递给每个线程以解决餐饮哲学家的问题。但是我收到了这个错误:

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
}

【问题讨论】:

  • pthread_create() 采用指针而不是 int。
  • 我改变了 pthread_create (&philo[i], NULL,(void *)philosopher,(void *)i);到 pthread_create (&philo[i], NULL,(void *)philosopher,(int *)i);还是不行.....
  • 为什么要将philosopher 转换为void *?那是错误的类型。
  • @RADAR:这里绝对不能传递i的地址。当那些线程试图访问它时,i 的值将是完全不可预测的,因为你只有一个变量,它正在改变,并且对它的访问是不同步的。它只会持续存在的事实不是问题。
  • @Paul Griffiths,你是对的

标签: c pthreads dining-philosopher


【解决方案1】:

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

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

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

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

代码启动五个线程。每个线程都被传递一个唯一的 ID(一个介于 0 和 4 之间的 int),它会在短暂的延迟后打印到控制台。延迟的目的是为了证明线程每个都将获得一个唯一的 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 );
}

【讨论】:

    猜你喜欢
    • 2016-03-04
    • 1970-01-01
    • 1970-01-01
    • 2010-10-11
    • 2019-02-07
    • 2013-01-28
    • 1970-01-01
    • 1970-01-01
    • 2010-10-26
    相关资源
    最近更新 更多