我已经编辑了我的问题。线程的运行方式似乎与我的预期不同(Windows 与 Linux)。这是完整的工作示例:
#include <pthread.h>
#include <stdio.h>
#include <string.h>
void *testing(void *mptr)
{
char *mystr;
mystr=(char *)mptr;
printf(mystr);
printf("finished running thread\n");
return NULL;
}
int main()
{
pthread_t mythread;
char *str1;
str1=malloc(50);
strcpy(str1,"Hello World\n");
printf(str1);
printf("About to start\n");
//pthread_create(&mythread, NULL, testing, str1);
printf("finished creating thread\n");
printf(str1);
free(str1);
return 0;
}
以上程序产生:
Hello world
About to start
finished creating thread
Hello World
请注意,我没有在其中创建线程 - 具体行已被注释掉。 然而,如果我不注释掉“pthread_create..”行,输出是零星的,有时有垃圾:
Hello world
About to start
finished creating thread
Hello World
&%¤&finished creating thread
有时乱码部分还好,有时显示为“o World”等
根据我在 google 上搜索到的信息,堆栈的共享方式与 Windows 的共享方式不同。
如何访问稍后在线程中主程序中分配的内存?我错过了什么吗?
最佳答案
也许您应该等待线程完成后再释放字符串?
pthread_join 是你的 friend 。
关于c - 如何与Linux中的线程共享主程序的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38775548/