c - pthreads 中的全局变量 [英] c - global variables in pthreads

查看:70
本文介绍了c - pthreads 中的全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在文件function.c中定义了一个函数,在main.c中创建了多个pthread来执行function.c中的函数

Suppose I defined a function in file function.c, and in main.c I create multiple pthreads to execute the function in function.c.

如果在function.c中,我定义了一个全局变量,例如int foo;

If in function.c, I define a global variable, for example, int foo;

那么,我的问题是,是每个线程都有自己的这个变量foo"的实例还是共享一个foo"?

Then, my question is, does every thread has its own instance of this variable "foo" or do they share a single "foo"?

推荐答案

它们共享一个 foo 变量.全局变量总是每个进程只存在一次,并且通常由互斥锁保护以避免并发访问.

They share a single foo variable. Global variable always exists only once per process and is usually protected by mutex to avoid concurrent access.

从 C11 开始,您可以使用 thread_local 将变量声明为每个线程的本地变量:

Since C11 you can use thread_local to declare the variable as local per thread:

#include <threads.h>
...
thread_local int perThreadInt;

这篇关于c - pthreads 中的全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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