本文介绍了将指针字符参数传递给线程中的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我执行这段代码时,我收到了一个细分错误(核心笨拙)。
#include< ; pthread.h>
#include< stdio.h>
void function(char * oz){
char * y;
y =(char *)oz;
** y =asd;
返回NULL;
}
int main(){
char * oz =oz\\\
;
pthread_t thread1;
if(pthread_create(& thread1,NULL,function,(void *)oz)){
fprintf(stderr,Error creating thread \\\
);
返回1;
if(pthread_join(thread1,NULL)){
fprintf(stderr,Error joining thread \\\
);
返回2;
}
printf(%s,oz);
返回0;
$ / code $ / pre
解决方案需要决定,如何管理内存:是由调用者分配的内存,还是在线程函数内部。
如果内存由调用者分配,那么线程函数看起来像:
void * function(void * arg)
{
char * p = arg;
strcpy(p,abc); // p指向由线程创建者分配的内存区域
返回NULL;
}
用法:
char数据[10] =oz; //分配10个字节并用'oz'初始化它们
...
pthread_create(& thread1,NULL,function,data);
如果内存是在线程函数内部分配的,那么您需要传递指针指针:
void * function(void * arg)
{
char ** p =(char ** )精氨酸;
* p = strdup(abc); //相当于malloc + strcpy
返回NULL;
}
用法:
char * data =oz; //数据可以指向只读区域
...
pthread_create(& thread1,NULL,function,& data); //传递指向变量
...
的指针free(data); //不需要数据 - 空闲内存 -
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\n";
pthread_t thread1;
if(pthread_create(&thread1,NULL,function,(void *)oz)){
fprintf(stderr, "Error creating thread\n");
return 1;
}
if(pthread_join(thread1,NULL)){
fprintf(stderr, "Error joining thread\n");
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;
}
Usage:
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;
}
Usage:
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-
这篇关于将指针字符参数传递给线程中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!