pthread_join会破坏堆栈中的pthread_create参数

时间:2015-02-17 23:34:34

标签: c linux multithreading

我从高级Linux编程书中获取了此代码。当我尝试在Linux 64位环境下执行代码时,which_prime函数调用后pthread_join()变量的值被破坏(更改为0)。

在此示例中,为什么运行pthread_join后which_prime的值会被损坏?

一般情况下,即使我们调用pthread_join()之类的其他函数,我们也能在main内部安全地使用传递给pthread_create函数的第四个参数吗?

#include <pthread.h>
#include <stdio.h>

/* Compute successive prime numbers (very inefficiently). Return the
Nth prime number, where N is the value pointed to by *ARG. */
void* compute_prime (void* arg)
{
    int candidate = 2;

    int n = *((int*) arg);
    while (1) {
        int factor;
        int is_prime = 1;
        /* Test primality by successive division. */
        for (factor = 2; factor < candidate; ++factor)
            if (candidate % factor == 0) {
                is_prime = 0;
                break;
            }
        /* Is this the prime number we’re looking for? */
        if (is_prime) {
            if (--n == 0)
                /* Return the desired prime number as the thread return value. */
                return (void*) candidate;
        }
        ++candidate;
    }
    return NULL;
}

int main ()
{
    pthread_t thread;
    int which_prime = 5000;
    int prime;
    /* Start the computing thread, up to the 5,000th prime number. */
    pthread_create (&thread, NULL, &compute_prime, &which_prime);
    /* Do some other work here... */
    /* Wait for the prime number thread to complete, and get the result. */
    pthread_join (thread, (void*) &prime);
    /* Print the largest prime it computed. */
    printf(“The %dth prime number is %d.\n”, which_prime, prime);
    return 0;
}

1 个答案:

答案 0 :(得分:4)

我们已经到达了intpointer之间转换不再安全的时间点。那是因为有64位系统,其中指针是64位,但int只有32位。

假设有32位int和64位指针,那么您的代码中会发生什么。 pthread_join的第二个参数是指向指针的指针。换句话说,您应该传递指针的地址(64位值的地址)。而是传递prime的地址(32位值的地址)。当pthread_join写入结果时,它会覆盖which_prime,因为which_prime跟在内存中的prime

要解决此问题,您需要避免在int和指针之间进行转换。一种方法是避免使用pthread_join的第二个参数,如以下代码所示。

#include <stdio.h>
#include <pthread.h>

#define NUM_THREADS 20

typedef struct
{
    int success;
    int input;
    int output;
} stData;

void *doSomething( void *arg )
{
    stData *dataptr = arg;

    dataptr->success = 1;
    dataptr->output  = dataptr->input * 2;
    return NULL;
}

int main( void )
{
    int i;
    pthread_t id[NUM_THREADS];
    stData data[NUM_THREADS] = {{0}};

    for ( i = 0; i < NUM_THREADS; i++ )
    {
        data[i].input = i + 1;
        pthread_create( &id[i], NULL, doSomething, &data[i] );
    }

    for ( i = 0; i < NUM_THREADS; i++ )
    {
        pthread_join( id[i], NULL );

        if ( data[i].success )
            printf( "thread %2d: input=%2d output=%2d\n", i+1, data[i].input, data[i].output );
        else
            printf( "thread %2d: failed\n", i+1 );
    }

    return 0;
}