如何锁定简单的字节数组
我有数据(“unsigned char data[480][640][4]”)和 两个线程
thisThread1FunctinIsCalledForExampleAbout50CallsPerSecond() { 填充(数据); //并填充数据 )
thisThread2FunctionIsCalledAbout1TimePerSecond( { 使用(数据); //及其使用数据(不仅读取而且处理它们)
}
我是多线程方面的新手,我面临一个基本问题: 我这里有“竞争条件” - 线程 1 更改并“破坏”数据,而线程 2“使用”数据 - 我应该做什么来防止它?
tnx 寻求答案,抱歉我的英语很差
i have data ("unsigned char data[480][640][4]") and
two threads
thisThread1FunctinIsCalledForExampleAbout50CallsPerSecond()
{
fill( data ); //and it fills the data
}
thisThread2FunctionIsCalledAbout1TimePerSecond()
{
use( data ); //and its uses the data (not only reads but also processes them)
}
I am totally newbie in multithreading and i am facing a basic problem:
I have got 'race conditions' here -
thread 1 changes and 'spoils' the data while thread 2 'uses' them
- what should i do to prevent it??
tnx for answers, sorry for my weak english
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我从来没有在 Objective C 中写过任何东西,但我的理解是你会做这样的事情来保护对数据的访问:
这个想法是使用锁来确保在任何时候只有一个线程正在访问数据。
如果您在处理数据(读取数据)时做了很多工作,那么您可能需要在锁内复制数据,然后退出锁。然后,您可以安全地使用您在锁内创建的数据的副本,而不必担心写入线程会在您下面更改它。
您希望锁定的时间尽可能短,因为如果长时间锁定,可能会阻塞其他线程并浪费资源。
如果您复制数据,则必须在锁内复制。
I've never written anything in objective c but my understanding is you would do something like this to protect access to your data:
The idea is to use a lock to make sure that only one thread is accessing the data at any one time.
If you are doing a lot of work while processing the data (reading it) then you might want to make a copy of the data inside a lock and then exit the lock. You can then safely use the copy of the data you created while inside the lock without worrying about the write thread changing it underneath you.
You want to keep the amount of time you are locked as short as possible as you are potentially blocking the other thread and wasting resources if you lock for long periods.
If you make a copy of the data you MUST make the copy inside a lock.