Tuesday, May 10, 2011

pThread mutex example in c/c++.

Following thread mutex lock example is collected from http://www.cs.cf.ac.uk/Dave/C/node32.html Mutex is used to synchronize access to the array data structure that
are shared by several threads.


#define _REENTRANT
#include <stdio.h>
#include <thread.h>

/* sample array data structure */
struct {
        mutex_t data_lock[5];
        int     int_val[5];
        float   float_val[5];
        } Data;

/* thread function */
void *Add_to_Value();

main()
{
int i;

/* initialize the mutexes and data */
for (i=0; i<5; i++) {
        mutex_init(&Data.data_lock[i], USYNC_THREAD, 0);
        Data.int_val[i] = 0;
        Data.float_val[i] = 0;
        }

/* set concurrency and create the threads */
thr_setconcurrency(4);

for (i=0; i<5; i++)
    thr_create(NULL, 0, Add_to_Value, (void *)(2*i), 0, NULL);

/* wait till all threads have finished */
for (i=0; i<5; i++)
        thr_join(0,0,0);

/* print the results */
printf("Final Values.....\n");

for (i=0; i<5; i++) {
        printf("integer value[%d] =\t%d\n", i, Data.int_val[i]);
        printf("float value[%d] =\t%.0f\n\n", i, Data.float_val[i]);
        }

return(0);
}


/* Threaded routine */
void *Add_to_Value(void *arg)
{
int inval = (int) arg;
int i;

for (i=0;i<10000;i++){
    mutex_lock(&Data.data_lock[i%5]);
       Data.int_val[i%5] += inval;
       Data.float_val[i%5] += (float) 1.5 * inval;
    mutex_unlock(&Data.data_lock[i%5]);
    }

return((void *)0);
}

Monday, May 9, 2011

NSThread Example 3

NSThread creation example by NSThread alloc and init.

NSThread *myThread = [[NSThread alloc] initWithTarget:self selector:@selector(threadFunc:) object:nil];
[myThread start];


Simple enough!

NSThread isCancelled example objc

[An NSThread isCancelled method example]

Create a NSThread object with following code fragment.


NSThread *newThread = [[NSThread alloc] initWithTarget:self selector:@selector(MyThread:) object:timer];

To stop this thread externally, you can call NSThread:cancel method at some
point and make your main thread method to check for whether it's cancelled or not
by calling NSThread isCancelled method.

In your main thread method, you should check whether it's cancelled or not periodically.


// At some checkpoint
if([[NSThread currentThread] isCancelled]) {
    /* do some clean up here */
    [NSThread exit];
}

performSelectorInBackground example objc

You can create a thread by simply calling NSObject:performSelectorInBackground:withObject: method.

[performSelectorInBackground example]

01: [objectA
02: performSelectorInBackground:@selector(doSomething)
03: withObject:myName];

NSInvocationOperation example objc

An NSInvocationOperation example. You can make a thread-like effect using NSInvocationOperation class. See Following code fragment.


First create a NSInvocationOperation object.
01: NSInvocationOperation* op =
02: [[[NSInvocationOperation alloc]
03: initWithTarget:self
04: selector:@selector(myMethod:) object:data] autorelease];
Next, you run the NSInvocationOperation object by queueing it into new NSOperationQueue object.
01: NSOperationQueue* queue = [[NSOperationQueue alloc] init];
02: [queue setMaxConcurrentOperationCount:1];
03: [queue addOperation:op];

NSThread example objc

A NSThread example that is very  simple.
Let's create and run a NSThread object on iPhoneOS.
First you should write a method that runs as a thread [NSThread Example]

1-(void) myTestThread:(id)anObject {
2
3     NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
4     //Your code here..
5     
6    [autoreleasepool release];
7    [NSThread exit];
8
9}


Then create a new NSThread object with detachNewThreadSelector method as following
code fragment. That's all pretty simple! [NSThread Example]

[NSThread detachNewThreadSelector:@selector(myTestThread:) toTarget:self withObject:nil];

NSThread Example objc

An NSThread example collected from http://iphoneappsmaker.tistory.com/516
When startThreadButtonPressed method is invoked, a new NSThread object is
created and detached with startTheBackgroundJob callback. This method
simples updates the progressbar. [NSThread Example]




- (IBAction) startThreadButtonPressed:(UIButton *)sender {

threadStartButton.hidden = YES;
threadValueLabel.text = @"0";
threadProgressView.progress = 0.0;
[NSThreaddetachNewThreadSelector:@selector(startTheBackgroundJob) toTarget:selfwithObject:nil];

}

- (void)startTheBackgroundJob {

NSAutoreleasePool *pool = [[NSAutoreleasePoolalloc] init];
// wait for 3 seconds before starting the thread, you don't have to do that. This is just an example how to stop the NSThread for some time
[NSThreadsleepForTimeInterval:3];
    [selfperformSelectorOnMainThread:@selector(makeMyProgressBarMoving) withObject:nilwaitUntilDone:NO];
    [pool release];

}

- (void) makeMyProgressBarMoving{

    
float actual = [threadProgressViewprogress];
threadValueLabel.text = [NSStringstringWithFormat:@"%.2f", actual];
if (actual < 1) {
threadProgressView.progress = actual + 0.01;
[NSTimerscheduledTimerWithTimeInterval:0.5target:selfselector:@selector(makeMyProgressBarMoving) userInfo:nilrepeats:NO];
}
elsethreadStartButton.hidden = NO;

}