0
char buff[MAX_SIZE];

int main() {

    pthread_t thread[3];

    char message1 = 17;  //17 = 0x11
    char message2 = 18;
    char message3 = 19;
    char message4 = 20;

    int iret[3];
    int k;

    char message[] = {17, 18,19,20};

    /*THIS IS WORKING  

    iret[0] = pthread_create( &thread[0], NULL, write_to_buffer, (void*) &message1);
    iret[1] = pthread_create( &thread[1], NULL, write_to_buffer, (void*) &message2);
    iret[2] = pthread_create( &thread[2], NULL, write_to_buffer, (void*) &message3);
    iret[3] = pthread_create( &thread[3], NULL, write_to_buffer, (void*) &message4);
    */


    /* BUT THIS IS NOT 

    iret[0] = pthread_create( &thread[0], NULL, write_to_buffer, (void*) message);
    iret[1] = pthread_create( &thread[1], NULL, write_to_buffer, (void*) (message+1));
    iret[2] = pthread_create( &thread[2], NULL, write_to_buffer, (void*) (message+2));
    iret[3] = pthread_create( &thread[3], NULL, write_to_buffer, (void*) (message+3));

    */

    for(k=0;k<=3;k++)   {
        pthread_join( thread[k], NULL);
    }


    //rest of main

}


void *write_to_buffer( void *ptr ) {

    while(1)    {
        pthread_mutex_lock(&my_mutex);


        char *message;
        message = (char *) ptr;

        //when passing by array I'm unable to get the value in the message variable

        printf("\nMeeee = %#x  ", *(char*)ptr);



        //REST OF THE FUNCTION //logic to write to buffer

        pthread_mutex_unlock(&my_mutex);

        //SOME LOGIC I OMMITED HERE
        //to return if(indexx >= MAX_SIZE) return(NULL);        
    }   
}

我面临的问题是,当我传递数组元素时,我无法捕获线程函数中的值。但是当我传递 message1、message2、message3 和 message4 的地址时,我能够获取线程函数中传递的值

4

1 回答 1

1

您的代码中有几个未定义行为的案例。您声明大小为 3 的threadiret数组,但创建了 4 个线程,从而覆盖这些数组的边界。这可能会影响程序的结果及其输出,因为它可能会导致您传递的数据被覆盖。

于 2013-10-28T09:28:01.167 回答