将指针 char 参数传递给线程中的函数 [英] passing pointer char argument to function in thread

查看:41
本文介绍了将指针 char 参数传递给线程中的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我执行此代码时,我收到分段错误(核心愚蠢)".

When I execute this code, I'm receiving a "segmentation error (core dumbed)".

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

void function(char *oz){

    char *y;
    y = (char*)oz;
    **y="asd";


    return NULL;
}

int main(){
    char *oz="oz
";

    pthread_t thread1;

    if(pthread_create(&thread1,NULL,function,(void *)oz)){
        fprintf(stderr, "Error creating thread
");
        return 1;
    }

    if(pthread_join(thread1,NULL)){
        fprintf(stderr, "Error joining thread
");
        return 2;
    }
    printf("%s",oz);
    return 0;

}

推荐答案

首先你需要决定,你想如何管理内存:是调用者分配的内存,还是线程函数内部.

First you need to decide, how you want to manage the memory: is the memory allocated by caller, or inside the thread function.

如果内存是由调用者分配的,那么线程函数将如下所示:

If the memory is allocated by caller, then the thread function will look like:

void *function(void *arg)
{
    char *p = arg;
    strcpy(p, "abc"); // p points to memory area allocated by thread creator
    return NULL;
}

用法:

char data[10] = "oz"; // allocate 10 bytes and initialize them with 'oz'
...
pthread_create(&thread1,NULL,function,data);

如果内存是在线程函数内部分配的,那么你需要传递指针到指针:

If the memory is allocated inside the thread function, then you need to pass pointer-to-pointer:

void *function(void *arg)
{
    char **p = (char**)arg;
    *p = strdup("abc"); // equivalent of malloc + strcpy
    return NULL;
}

用法:

char *data = "oz"; // data can point even to read-only area
...
pthread_create(&thread1,NULL,function,&data); // pass pointer to variable
...
free(data); // after data is not needed - free memory-

这篇关于将指针 char 参数传递给线程中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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