开发者

linux c-pthreads: problem with local variables

trying to calculate fibonacci's number with threads. It always return 1. Any suggestions?

my code:

#include <stdio.h>  
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
/* compile with -lpthread */
void*  fibo (void* param) {
    int    a,b,n;
    pthread_t thread_a, thread_b;
    int ret;

    n = (int) param;
    if (n>1)
    {    pthread_create(&thread_a,NULL,fibo,(void*)(n-1));    
        pthread_create(&thread_b,NULL,fibo,(void*)(n-2));
        pthread_join(thread_a,(void**)&a);
        pthread_join(thread_b,(vo开发者_运维知识库id**)&b);
        ret=a+b;
    }
    else    ret=1;
    return (ret);    
    /*pthread_exit((void**)ret);*/
}

int main(int argc,char* argv[]) {
    pthread_t thread_id;
    int n,ret;
    n=atoi(argv[1]);
    pthread_create(&thread_id,NULL,fibo,(void*)n);
    pthread_join(thread_id,(void**)&ret);
    printf("s(%d)=%d\n",n,ret);
    return 0;
}


I'm guessing that you're probably on a 64-bit system.

Your problem is in the pthread_join:

int n,ret;
pthread_join(thread_id,(void**)&ret);

On 64-bit systems, ints are 32 bits, but void*s are 64 bits. So you're trying to store 64 bits in a 32-bit-wide variable. As as result, you overwrite other locations on the stack and just generally make a huge mess of things. Make sure to retrieve the value into a true void * and things ought to work better. Better yet, use the void* pointer as a true pointer; for example, you could pass a pointer to an int as the thread function argument, and use that as the argument, then write the result to the same location.

Incidentally, GCC warns about this, even without any warning switches:

test.c:30: warning: cast to pointer from integer of different size

Please don't ignore these warnings.


There's an error:

n = (int) param;

whereas param is an void*. so, you convert a pointer to an int, which is likely yilds a negative number, and the control passes to the else branch :)

EDIT: but there still may be a caveat here: error: cast from 'void*' to 'int' loses precision


Threads do not use the same local variables, since local variables are on the stack, and each thread has its own stack. Threads do share global variables unless they are made explicitly thread-local.

You can create thread-local storage in pthreads using pthread_key_create and related functions.

(as vines points out, this is beside the point as your error is not really thread-related)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜