小编Yur*_*urt的帖子

堆栈如何在使用 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;
}
Run Code Online (Sandbox Code Playgroud)

第二个程序运行有问题

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

int i = 0;

void *thr(void *arg)
{
   for(; i < 50; i++)
     printf("Thread = %zu Value= %d\n", …
Run Code Online (Sandbox Code Playgroud)

c multithreading posix pthreads thread-synchronization

4
推荐指数
1
解决办法
1257
查看次数