本文介绍了如何在 C++ 中使函数线程安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个包含 5 个子线程的线程池.他们正在调用一个名为functionA()"的函数如何使该函数成为线程安全的?

Let's say I have a thread pool that has 5 child threads. And they are calling a function called "functionA()" How do I make the function to be thread safe?

另外,如果这 5 个线程同时被调用,那么它们是并发执行的吗?或者他们是否等到当前在函数中工作的线程完成?

Also if those 5 threads are called at the same time then are they executed concurrently? or do they wait until a thread that currently works in the function to be finished ?

提前致谢..

推荐答案

如果一个函数不修改非本地内存并且不调用任何执行该操作的函数,它就已经是线程安全的.在这种(微不足道的)情况下,您无需执行任何操作.

A function is already thread safe if it doesn't modify non-local memory and it doesn't call any function that does. In this (trivial) case, you don't have to do anything.

您确实想考虑保护数据,而不是功能.例如,假设该函数修改了非本地数据结构 X.提供一个互斥锁来保护 X 并在每次访问之前锁定它并在之后解锁它.您可能有多个访问 X 的函数(例如 insertX()、deleteX()、...).只要你保护数据,你就没事.

You really want to think about protecting data, not functions. For example, let's say that the function modifies non-local data structure X. Provide a mutex to protect X and lock it before each access and unlock it after. You may have more than one function that accesses X (e.g. insertX(), deleteX(), ...). As long as you protect the data you'll be OK.

这篇关于如何在 C++ 中使函数线程安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 16:26
查看更多