“解铸造” from(void *)和解引用到char数组 [英] "Un-casting" from (void *) and de-referencing to char array

查看:440
本文介绍了“解铸造” from(void *)和解引用到char数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我几乎完成了一项家庭作业,我需要使用pthreads。我已经找出了pthreads。我剩下的唯一的问题是弄清楚如何通过pthread_create()传递多个参数到线程。

I have almost completed an homework assignment where I am required to use pthreads. I have figured out the pthreads. The only problem I have left is figuring out how to pass multiple arguments to threads through pthread_create().

我需要传递两个字符到线程。我必须将它们转换(* void)以与pthread_create()一起使用。我可以通过它们,但我不知道如何从函数中的*参数获取值。

I need to pass two chars to the thread. I have to cast them to (*void) to use with pthread_create(). I can pass them, but I can't figure out how to get the values from *parameter in the function.

void *my_function(void *parameter) {

    /* ATTEMPT 1 - DOESN'T WORK */
    //char* arguments[2];
    //arguments = (char * [2]) parameter;
    /*Error message: 
    error: ISO C++ forbids casting to an array type char* [2] [-fpermissive]
    error: incompatible types in assignment of char** to char*[2]
    */

    /* ATTEMPT 2 - DOESN'T WORK */
    //char *my_data = (char *)parameter;
    //my_data is blank when I try to use cout to check it's values

    /* What I need to do is get those two chars from the array and print them out as part of this thread function */

    pthread_exit(NULL);
}

int main(int argc, char **argv) {

    char duration = '5'; //in reality, this value is taken from argv but I am leaving that out for brevity

    pthread_t threads[3];

    for(int i=0; i < 3; i++){

         char thread_args[2] = {i, duration};

         //create thread with arguments passed in
         int results = pthread_create(&threads[i], NULL, my_function, (void *) &thread_args);

         //testing for pthread error
         if (results){
             printf("ERROR; return code from pthread_create() is %d\n", results);
             exit(-1);
         }

     }

    /* Wait for all threads to complete */
    for (int j=0; j < num_threads; j++) { // https://computing.llnl.gov/tutorials/pthreads/
        pthread_join(threads[j], NULL);
    }


    /* some information prints here that is unrelated to my problem (the date, time, etc) */

    pthread_exit(NULL);
}

我可以传递一个值,没有问题。任何建议?

I was able to pass one value through with no problem. Any suggestions?

我可以找到的最接近的现有问题是,但我还没有运气:在C中将void *转换为char **

The closest existing question I could find was this but I still am having no luck: Converting from void* to char ** in C

谢谢! / p>

Thank you!

推荐答案

请注意,在此循环中:

for(int i=0; i < 3; i++){
    char thread_args[2] = {i, duration};
    int results = pthread_create(&threads[i], NULL, my_function, (void *) 
    ...
}

thread_args 是一个具有自动存储持续时间的本地数组,其生命周期与每次迭代相关,在这种情况下,存储这些参数的内存可能会在线程访问它之前释放,这将导致未定义的行为

thread_args is a local array with automatic storage duration, lifetime of which is tied to each iteration so there is a chance that the memory where you store these arguments might be freed before the thread will access it, which would lead to undefined behavior in that case.

更好的方法是创建一个结构体,你可以用来传递数据到这个线程:

Much better approach would be to create a structure, that you would use to pass the data to this thread:

typedef struct {
    char duration;
    int num;
} ThreadData;

然后你的代码看起来像这样:

Then your code could look like this:

void *my_function(void *parameter) {
    // retrieve and print the thread data:
    ThreadData* td = (ThreadData*) parameter;
    printf("num = %d, duration = %c\n", td->num, td->duration);
    delete td;
    return NULL;
}

int main(int argc, char **argv) {
    char duration = '5';
    pthread_t threads[3];

    for (int i = 0; i < 3; i++) {
        // create structure that will be passed to thread:
        ThreadData* td = new ThreadData;
        td->duration = duration;
        td->num = i;

        //create thread with arguments passed in:
        int ret = pthread_create(&threads[i], NULL, my_function, (void *) td);

        //testing for pthread error:
        if (ret) {
            printf("ERROR; return code from pthread_create() is %d\n", ret);
            exit(-1);
        }
    }
    // wait for all threads to complete:
    for (int i = 0; i < 3; i++) {
        pthread_join(threads[i], NULL);
    }
    exit(0);
}

还要注意,要结束线程的执行,最好使用<$ c $因为使用 return ,可以保证线程例程中的变量将会被毁坏,堆叠将被解开。有关详细信息,请参阅pthread启动函数中的 return()与pthread_exit()

Also note that to end thread's execution it is better to use return than pthread_exit since with return it is guaranteed that variables within thread's routine will be destroyed and stack will be unwound. For more information see return() versus pthread_exit() in pthread start functions

这篇关于“解铸造” from(void *)和解引用到char数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆