静态变量和线程(C) [英] Static Variables and Threads (C)

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

问题描述

我知道在C函数中声明一个静态变量意味着该变量在函数调用之间保留其状态.在线程上下文中,这会导致变量在多个线程上保持其状态,还是在每个线程之间具有单独的状态 ?

I know that declaring a static variable within a function in C means that this variable retains its state between function invocations. In the context of threads, will this result in the variable retaining its state over multiple threads, or having a separate state between each thread?

这是我在努力回答的过去的纸质考试问题:

Here is a past paper exam question I am struggling to answer:

以下C函数旨在用于为其调用方分配唯一标识符(UID):

get_uid() 
{
static int i = 0;
return i++;
}

说明在多个线程调用get_uid()的环境中,get_uid()可能以何种方式无法正常工作.用一个 具体的示例场景,请详细说明为什么以及如何这样做 可能会发生错误的行为.

Explain in what way get_uid() might work incorrectly in an environment where it is being called by multiple threads. Using a specific example scenario, give specific detail on why and how such incorrect behaviour might occur.

目前,我假设每个线程的变量都有单独的状态,但是我不确定这是否正确,或者答案是否与缺少互斥性有关.如果是这样,那么在此示例中如何实现信号量?

At the moment I am assuming that each thread has a separate state for the variable, but I am not sure if that is correct or if the answer is more to do with the lack of mutual exclusion. If that is the case then how could semaphores be implemented in this example?

推荐答案

您的假设(线程有自己的副本)不正确.代码的主要问题是,当多个线程调用该函数get_uid()时,可能存在竞争条件,即哪些线程递增i并获取可能不是唯一的ID.

Your assumption (threads have their own copy) is not correct. The main problem with code is when multiple threads call that function get_uid(), there's a possible race condition as to which threads increments i and gets the ID which may not be unique.

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

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