How do I safely populate an array from one thread while reading it in another in Objective-C?

First off I'm not that familiar with using threads and i'm learning on the fly. I have an array that is being used in thread a and being populated in thread b. What I want to do is find the best practice for waiting for the array to be populated from thread b before using it in thread a.

-------------Problems Reply------------

You can either copy the array in the reading thread so that it does not change while you read it, or you can @synchronize the access to the array:

- (void) writer
[theArray addObject:foo];

- (void) reader
for (id item in theArray)
[item …];

I haven't used Objective C but what you're looking for is a Condition Lock. This is a type of lock (mutex) that prevents threads from accessing locked data but keeps a queue of all the threads that asked for permission (often using a semaphore). When the data becomes unlocked, the Condition Lock automatically wakes up the requesting threads.

In your case, the array will be locked by thread B while its being populated. When thread A tries to access the array, it will yield because thread B currently holds the lock. When thread B is finished, it will see that thread A tried to access the array while it was locked and wake up thread A. Thread A can then safely access the array.

Here's the first result after a google search for Condition Locks in Objective C. It's about the iPhone API, but might be useful nonetheless:

The answer depends somewhat on what you are doing with the array contents.

To some degree, the question does not make a lot of sense - if thread a has to wait until the entire array is populated in thread b, then why not just do the populating work in thread a? What else is it doing while waiting for the array?

Alternatively, if thread a can make forward progress as it receives each element of the array, then it may make more sense to pass each received array entry from thread b to thread a as they are created. In that case you effectively have a queue, which is a common producer/consumer pattern for threaded work - thread b fills up a queue which thread a reads from.

See the "Using an NSConditionLock Object" section of the link Kai posted for an example producer/consumer lock.

Category:iphone Views:0 Time:2009-06-07

Related post

  • Correct way to populate an Array with a Range in Ruby 2008-10-10

    I am working through a book which gives examples of Ranges being converted to equivalent arrays using their "to_a" methods When i run the code in irb I get the following warning warning: default `to_a' will be obsolete What is the the correct alterna

  • What's the fastest way to populate an array with numbers in PHP? 2009-09-03

    What's the fastest way to populate an array with the numbers 1-100 in PHP? I want to avoid doing something like this: $numbers = ''; for($var i = 0; i <= 100; $i++) { $numbers = $i . ','; } $numberArray = $numbers.split(','); It seems long and ted

  • Does JavaScript populate empty array items? 2010-01-11

    I am coding a lot of annual data in JavaScript, and I was considering adding it to arrays, using the year as the array index and putting the data into the array. However, Firebug seems to be indicating that JavaScript handles this by populating two t

  • How can I populate javascript array using XSLT (Reading values from XML) 2010-02-23

    I have the following requirement. I need to populate a javascript array with values reading from an input XML file using XSLT. I just need to read XML using XSLT and populate an array in javascript. Can anybody has any idea regarding this, it would o

  • How to populate an array with recordset data 2010-03-08

    I am attempting to move data from a recordset directly into an array. I know this is possible, but specifically I want to do this in VBA as this is being done in MS Access 2003. Typically I would do something like the following to achieve this: Dim v

  • Populate an array to consist of all of the values in an html select list using jQuery 2010-12-01

    I have an HTML select list (let's call it List A) that is dynamically populated with a list of values. I need to change another select list (List B) depending on the value of List A. That part, I can do. Ordinarily, the user selects one element of Li

  • JQuery, AJAX: How can I populate an array with a json return? 2010-12-30

    I'm trying to following code but only get "undefined" in the alert box. Anyone know how I can actually populate the array outside of the .ajax? $(document).ready(function() { var reviewArray = new Array(); getReviews(); alert(reviewArray[0]); }); fun

  • How does one populate an array in Ruby? 2011-01-04

    Here is the code I'm working with: class Trader def initialize(ticker ="GLD") @ticker = ticker end def yahoo_data(days=12) require 'yahoofinance' YahooFinance::get_historical_quotes_days( @ticker, days ) do |row| puts "#{row.join(',')}" # this is whe

  • How to populate an array in javascript using data sent through Model List 2011-03-21

    I have a list in my model, EmployeeList In my View I want to to populate an array from EmployeeList(from Model) and use it as autocomplete for tags. It seems that the array isn`t being poplulated from the List nor is the autocomplete working. Help pl

  • Best way to populate this array using .txt file? 2011-07-14

    I'm looking to make SEVERAL arrays populated with words. Eventually I want to be able to just pull a random word from the array and display it (I've mastered that). What I'm wondering is what is the best way to populate this array. Should I just type

  • Populate php array from mysql with different values for the same array index 2011-11-18

    I have a mysql DB with those column id , idUser , idCompany , idProfession for users table. Now i would Select all those field and make an array that is build in this way : array[idUser] = array [id=> x , idCompany => xx , idProfession => xx

  • JSON using Tableview to populate the array 2011-12-22

    I m using tableview to populate an array from json file...In my view Controller i have tableview.when i run the project my table view codings are not executing.i dont know y?anyone help me pls.This is my viewcontroller file #import "JSONparserViewCon

  • populate an array with jQuery.children()? 2012-01-21

    simple question mainly for simplifying purposes but... currently using var categoryList = []; $('#share').children().each(function() { categoryList.push($(this).html()); }); I was curious if there was a way to just populate the array in 1 go... I rea

  • bash populate an array in loop 2012-04-02

    How can i populate an array in loop? I'd like to do something like that: declare -A results results["a"]=1 results["b"]=2 while read data; do results[$data]=1 done for i in "${!results[@]}" do echo "key : $i" echo "value: ${results[$i]}" done But it

  • Populate an array/list with sums 2012-04-28

    How can I populate an array or list with sums that don't go higher than 10? I could do this with 3 arrays where 2 of them hold random numbers which the answer is not higher than 10, and a 3rd array to have the answers in it. But that's kind of an ugl

  • Populate int array with for loop in Java 2014-04-29

    I have an array named numbers that I want to populate with a for loop: int[] numbers; for ( int i = 0; i <=10; i++) { // want to populate the array with a sequence of 0-10 } How can I populate the 11 values generated from the above for loop into m

  • How do I safely populate with data and Refresh() a DataGridView in a multi-threaded application? 2008-11-03

    My app has a DataGridView object and a List of type MousePos. MousePos is a custom class that holds mouse X,Y coordinates (of type "Point") and a running count of this position. I have a thread (System.Timers.Timer) that raises an event once every se

  • Arrays scoping in threads 2011-02-11

    How are arrays scoped in C? When do they ever get destroyed? (Note, also talk about if they can be passed even in p_threads) --------------Solutions------------- They're scoped just like normal variables: // in a function int arrayA[300]; { float arr

  • Do the keys of javascript associative arrays need to be strings, or can they be any object? 2009-02-04

    Do the keys of javascript associative arrays need to be strings, or can they be any object? --------------Solutions------------- There are no native associative arrays in JavaScript, only objects. Objects have properties. The names of properties are

Copyright (C), All Rights Reserved.

processed in 0.165 (s). 11 q(s)