c - 栈在使用Pthread的多线程程序中是如何工作的?

我有一个简单的问题,我相信,据我所知,一个多线程程序,它们在所有线程之间共享进程的内存空间,包括,堆栈,全局内存区域,文件描述符等,我我想知道为什么在第一个例子中,存在一致性问题,因为理论上所有线程共享堆栈,在第二个例子中,出现竞争问题。

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

void *thr(void *arg)
{
   for(int i = 0; i < 50; i++)
       printf("Thread = %zu Value= %d\n", pthread_self(), i);
   return NULL;
}

int main(void)
{
   pthread_t threads[2];
   for(int i = 0; i < 2; i++)
     pthread_create(&threads[i], NULL, thr, NULL);
   for(int i = 0; i < 2; i++)
     pthread_join(threads[i], NULL);
   return 0;
}

第二个程序运行有问题

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

int i = 0;

void *thr(void *arg)
{
   for(; i < 50; i++)
     printf("Thread = %zu Value= %d\n", pthread_self(), i);
   return NULL;
}

int main(void)
{
   pthread_t threads[2];
   for(int i = 0; i < 2; i++)
     pthread_create(&threads[i], NULL, thr, NULL);
   for(int i = 0; i < 2; i++)
     pthread_join(threads[i], NULL);
   return 0;
}

3 竞争问题的示例,在这种情况下,变量在主线程中创建并作为参数传递给函数,也就是说,唯一的共享堆栈来自主线程?

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

void *thr(void *arg)
{
   int *ptr = (int *)arg;
   for(; *ptr < 50; (*ptr)++)
     printf("Thread = %zu Value= %d\n", pthread_self(), *ptr);
   return NULL;
}

int main(void)
{
   int i = 0;
   pthread_t threads[2];
   for(int i = 0; i < 2; i++)
     pthread_create(&threads[i], NULL, thr, &i);
   for(int i = 0; i < 2; i++)
     pthread_join(threads[i], NULL);
   return 0;
}

最佳答案

share the process's memory space between all threads, that includes, stack

嗯,是和不是。

共享内存地址空间和特定内存区域是有区别的。

虽然所有线程确实共享一个地址空间,但每个线程都有自己的堆栈(内存分配)。

共享地址空间意味着给定的虚拟地址(指针值)在所有线程中引用相同的物理内存。

但是专用堆栈意味着每个线程的堆栈指针都从该地址空间中的不同位置开始,以免彼此冲突。

https://stackoverflow.com/questions/69170267/

相关文章:

html - 使 flexbox 垂直增长

c++ - 如何在给定输入的数字中找到最大的数字?

laravel - Laravel 中的 getClientOriginalExtension()

android - 从协程(kotlin)切换到隔离(dart)

python - Azure Databricks python 命令显示当前集群配置

html -

  • 上的背景图像变为背景而不是列表元素符号

    r - 如何在 R 中为函数添加红线

    java - 为什么 java 编译器不提示 "\s"?

    python - 如何找到中轴的关节和端点

    c++ - 如何获取属于某个范围的 vector 中的最大元素?