线程内带有 malloc 的变量 [英] Variable with malloc inside a thread

查看:58
本文介绍了线程内带有 malloc 的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于 pthread 的问题,当我使用 malloc 在线程内创建一个变量,然后将其指针传递给共享结构,即 fifo,thread-1 传递的指针是否会被 thread2 访问?

I have a question about pthread, when I create a variable inside a thread with malloc and then pass its pointer to a shared structure, i.e fifo, is the pointer passed by thread-1 will be accessed by thread2 ?

请注意,我必须为上面的问题编写代码,我只是想更好地理解线程,下面就是我的想法.环境是pthreadclinux

Please note that I have to code for the question above, I'm just trying to understand threading better, the below is just what I'm thinking about. The environment is pthread, c and linux

据我所知,线程正在共享其父进程的内存,如果是这种情况,以下应该是正确的.

As far as I know threads are sharing the memory of their parent process, If that's the case the below should be correct.

void *thread-1(void *pointer)
{
  int *intp = malloc(4);
  send_to_fifo(intp);
}


void *thread-2(void *pointer)
{
  int *iptr;
  iptr = read_from_fifo();
  do_something(iptr);
  free(iptr);
}

推荐答案

线程 1 传递的指针是否会被线程 2 访问?

is the pointer passed by thread-1 will be accessed by thread2 ?

是的:因为所有线程都在一个公共内存空间中运行,所以这是允许的.

Yes: since all threads operate in a common memory space, this is allowed.

mallocfree 和其他内存管理函数默认是线程安全的,除非使用 NO_THREADS 编译.

malloc, free, and other memory management functions are thread-safe by default, unless compiled with NO_THREADS.

这篇关于线程内带有 malloc 的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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