开发者

how to lock simple array of bytes

开发者 https://www.devze.com 2023-02-25 19:00 出处:网络
i have data (\"unsigned char data[480][640][4]\") and two threads thisThread1FunctinIsCalledForExampleAbout50CallsPerSecond()

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??

开发者_StackOverflow

tnx for answers, sorry for my weak english


I've never written anything in objective c but my understanding is you would do something like this to protect access to your data:

lock = [[NSLock alloc] init];

readData(){
        [lock lock];
//read the data here
       [lock unlock];
}

writeDate(){
        [lock lock];
//write the data here
       [lock unlock];
}

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消