Saturday, May 7, 2011

removing whitespace of NSString

An example for removing whitespace of NSString. I doubt that this function is that useful. Anyway, methods for these job are provided. [removing whitespace of NSString]

1. Removes tabs and other whitespaces.
NSString *newString = [oldString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

2 Removes tabs, whitespaces and newlines.
NSString *newString = [oldString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

Friday, May 6, 2011

NSString stringByAppendingString example objc

Some NSString stringByAppendingString methods are listed below. One is creating new NSString object from two NSString objects and the other is using NSMutableString class.

1. NSString concatenation by creating a new NSString object from two NSString objects.

NSString *string1 = @"This is";
NSString *string2 = @" a test.";
NSString *string3 = [string1 stringByAppendingString:string2];
 or

NSString *string1 = @"This is";
NSString *string2 = @" a test.";
string1 = [string1 stringByAppendingString:string2];

2. NSString concatenation using NSMutableString object.
NSMutableString *string1 = @"This is";
NSString *string2 = @" a test.";
[string1 appendString:string2];

Objective C Math Constants

List of Objective C Math Constants.
Some important  math constants are M_PI, M_PI_2, M_PI_4.


#define M_E         2.71828182845904523536028747135266250   /* e */
#define M_LOG2E     1.44269504088896340735992468100189214   /* log2(e) */
#define M_LOG10E    0.434294481903251827651128918916605082  /* log10(e) */
#define M_LN2       0.693147180559945309417232121458176568  /* loge(2) */
#define M_LN10      2.30258509299404568401799145468436421   /* loge(10) */
#define M_PI        3.14159265358979323846264338327950288   /* pi */
#define M_PI_2      1.57079632679489661923132169163975144   /* pi/2 */
#define M_PI_4      0.785398163397448309615660845819875721  /* pi/4 */
#define M_1_PI      0.318309886183790671537767526745028724  /* 1/pi */
#define M_2_PI      0.636619772367581343075535053490057448  /* 2/pi */
#define M_2_SQRTPI  1.12837916709551257389615890312154517   /* 2/sqrt(pi) */
#define M_SQRT2     1.41421356237309504880168872420969808   /* sqrt(2) */
#define M_SQRT1_2   0.707106781186547524400844362104849039  /* 1/sqrt(2) */

#define    MAXFLOAT    0x1.fffffep+127f

NSStringEncoding table.

NSStringEncoding Table.

1NSASCIIStringEncoding Western (ASCII) US-ASCII
2NSNEXTSTEPStringEncoding Western (NextStep) X-NEXTSTEP
3NSJapaneseEUCStringEncoding Japanese (EUC) EUC-JP
4NSUTF8StringEncoding Unicode (UTF-8) UTF-8
5NSISOLatin1StringEncoding Western (ISO Latin 1) ISO-8859-1
6NSSymbolStringEncoding Symbol (Mac OS) X-MAC-SYMBOL
7NSNonLossyASCIIStringEncoding Non-lossy ASCII
8NSShiftJISStringEncoding Japanese (Windows, DOS) CP932
9NSISOLatin2StringEncoding Central European (ISO Latin 2) ISO-8859-2
10NSUnicodeStringEncoding Unicode (UTF-16) UTF-16
11NSWindowsCP1251StringEncoding Cyrillic (Windows) WINDOWS-1251
12NSWindowsCP1252StringEncoding Western (Windows Latin 1) WINDOWS-1252
13NSWindowsCP1253StringEncoding Greek (Windows) WINDOWS-1253
14NSWindowsCP1254StringEncoding Turkish (Windows Latin 5) WINDOWS-1254
15NSWindowsCP1250StringEncoding Central European (Windows Latin 2) WINDOWS-1250
21NSISO2022JPStringEncoding Japanese (ISO 2022-JP) ISO-2022-JP
30NSMacOSRomanStringEncoding Western (Mac OS Roman) MACINTOSH
-1677721344
Unicode (UTF-32LE) UTF-32LE
-1744830208
Unicode (UTF-32BE) UTF-32BE
-1811939072
Unicode (UTF-16LE) UTF-16LE
-1879047936
Unicode (UTF-16BE) UTF-16BE
-1946156800
Unicode (UTF-32) UTF-32
-2147480574
Western (EBCDIC Latin 1) IBM037
-2147481079
Traditional Chinese (Big 5-E)
-2147481080
Ukrainian (KOI8-U) KOI8-U
-2147481082
Traditional Chinese (Big 5 HKSCS) Big5-HKSCS
-2147481083
Simplified Chinese (HZ GB 2312) HZ-GB-2312
-2147481084
Western (Mac Mail) X-MAC-ROMAN-LATIN1
-2147481085
Traditional Chinese (Big 5) BIG5
-2147481086
Cyrillic (KOI8-R) KOI8-R
-2147481087
Japanese (Shift JIS) SHIFT_JIS
-2147481280
Korean (EUC) EUC-KR
-2147481295
Traditional Chinese (EUC) EUC-TW
-2147481296
Simplified Chinese (EUC) EUC-CN
-2147481536
Korean (ISO 2022-KR) ISO-2022-KR
-2147482062
Chinese (GB 18030) GB18030
-2147482063
Chinese (GBK) GBK
-2147482072
Japanese (Shift JIS X0213) Shift_JIS
-2147482360
Vietnamese (Windows) WINDOWS-1258
-2147482361
Baltic Rim (Windows) WINDOWS-1257
-2147482362
Arabic (Windows) WINDOWS-1256
-2147482363
Hebrew (Windows) WINDOWS-1255
-2147482589
Traditional Chinese (Windows DOS), CP950
-2147482590
Korean (Windows DOS), CP949
-2147482591
Simplified Chinese (Windows DOS), CP936
-2147482595
Thai (Windows DOS), CP874
-2147482596
Greek (DOS Greek 2) IBM869
-2147482597
Cyrillic (DOS) CP866
-2147482598
Nordic (DOS)
-2147482599
Arabic (DOS) cp864
-2147482600
Canadian French (DOS)
-2147482601
Hebrew (DOS) DOS-862
-2147482602
Icelandic (DOS) CP861
-2147482603
Portuguese (DOS)
-2147482604
Turkish (DOS) CP857
-2147482605
Cyrillic (DOS)
-2147482606
Central European (DOS Latin 2) CP852
-2147482607
Greek (DOS Greek 1)
-2147482608
Western (DOS Latin 1) CP850
-2147482618
Baltic Rim (DOS) CP775
-2147482619
Greek (DOS) CP737
-2147482624
Latin-US (DOS) CP437
-2147483120
Romanian (ISO Latin 10) ISO-8859-16
-2147483121
Western (ISO Latin 9) ISO-8859-15
-2147483122
Celtic (ISO Latin 8) ISO-8859-14
-2147483123
Baltic Rim (ISO Latin 7) ISO-8859-13
-2147483125
Thai (ISO 8859-11) ISO-8859-11
-2147483126
Nordic (ISO Latin 6) ISO-8859-10
-2147483127
Turkish (ISO Latin 5) ISO-8859-9
-2147483128
Hebrew (ISO 8859-8) ISO-8859-8
-2147483129
Greek (ISO 8859-7) ISO-8859-7
-2147483130
Arabic (ISO 8859-6) ISO-8859-6
-2147483131
Cyrillic (ISO 8859-5) ISO-8859-5
-2147483132
Central European (ISO Latin 4) ISO-8859-4
-2147483133
Western (ISO Latin 3) ISO-8859-3
-2147483412
Inuit (Mac OS)
-2147483496
Cyrillic (Mac OS Ukrainian) X-MAC-UKRAINIAN
-2147483508
Farsi (Mac OS) X-MAC-FARSI
-2147483607
Keyboard Symbols (Mac OS)
-2147483608
Gaelic (Mac OS)
-2147483609
Celtic (Mac OS)
-2147483610
Romanian (Mac OS) X-MAC-ROMANIAN
-2147483611
Icelandic (Mac OS) X-MAC-ICELANDIC
-2147483612
Croatian (Mac OS) X-MAC-CROATIAN
-2147483613
Turkish (Mac OS) X-MAC-TURKISH
-2147483614
Dingbats (Mac OS) X-MAC-DINGBATS
-2147483619
Central European (Mac OS) X-MAC-CENTRALEURROMAN
-2147483622
Tibetan (Mac OS) X-MAC-TIBETAN
-2147483623
Simplified Chinese (Mac OS) X-MAC-SIMP-CHINESE
-2147483627
Thai (Mac OS) X-MAC-THAI
-2147483637
Gujarati (Mac OS) X-MAC-GUJARATI
-2147483638
Gurmukhi (Mac OS) X-MAC-GURMUKHI
-2147483639
Devanagari (Mac OS) X-MAC-DEVANAGARI
-2147483641
Cyrillic (Mac OS) X-MAC-CYRILLIC
-2147483642
Greek (Mac OS) X-MAC-GREEK
-2147483643
Hebrew (Mac OS) X-MAC-HEBREW
-2147483644
Arabic (Mac OS) X-MAC-ARABIC
-2147483645
Korean (Mac OS) X-MAC-KOREAN
-2147483646
Traditional Chinese (Mac OS) X-MAC-TRAD-CHINESE
-2147483647
Japanese (Mac OS) X-MAC-JAPANESE

NSString search using NSRange example

An example code for matching NSString object using NSRange.


- (BOOL)matchString:(NSString *)theString withString:(NSString*)withString {
NSRange range = [theString rangeOfString:withString];
int length = range.length;
if (length == 0) {
return NO;
}
return YES;
}

iOS measure text size - UIFont example

You can measure text size using NSString:font:withinSize:lineBreakMode: method.
It's very useful to compute the height of tableviewcell or others. See following code.
[measure text size]

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *text = @"텍스트 크기 계산"
UIFont *font = [UIFont systemFontOfSize:14.0f]; 
CGSize withinSize = CGSizeMake(tableView.width, FLT_MAX); 
CGSize size = [text sizeWithFont:font constrainedToSize:withinSiz lineBreakMode:UILineBreakModeWordWrap];
return size.height + somePadding;
}

Background method execution using NSThread code example objc

You can execute a method in background mode using detachNewThreadSelector method. For proper memory management, the target method maintains its own AutoreleasePool. [detachNewThreadSelector]


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

-(void) doSomethingInBack:(id)anObject {
NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
// 다른 스레드로 실행할 코드 작성.p
[NSThread exit];
// 메모리 릭 방지.
[autoreleasepool release];
}

NSString writeToFile example objc

An example of saving NSString to a text file using NSString:writeToFile: method.
NSString:writeToFile: method takes four arguments; filename, atomic or not, encoding, error code. Nothing difficult in this code, enjoy!

Example - [NSString writeToFile]
-(void) writeToTextFile {
// Document 디렉토리.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// 데이터를 저장할 파일명 생성.
NSString *fileName = [NSString stringWithFormat:@"%@/textFile.txt", documentsDirectory];

// 파일의 내용 생성.
NSString *content = @"One\nTwo\nThree\nFour\nFive";

// Document 디렉토리에 저장.
[content writeToFile:fileName 
  atomically:NO 
encoding:NSStringEncodingConversionAllowLossy 
  error:nil];
}

openURL with Safari in iPhone

An example showing how to open an url with Safari. It's quit simple. You can open an url with Safari just like it's an internal method.

NSURL *url = [[NSURL alloc] initWithString: @"http://samplecodebank.blogspot.com/"];
[[UIApplication sharedApplication] openURL:url];

Getting current method name in objective C

Following code fragments shows some useful tips of NSLog method. __PRETTY_FUNCTION__ identifier is used to get current method name.
You can display hexa values using NSLog method with %x formatter.
NSLog(@"Hex value: 0x%08x", 0x1234);

You can even get current method name in execution using NSLog method.

NSLog(@"%s", __PRETTY_FUNCTION__, nil);

NSLog example

Following code fragments shows some useful tips of NSLog method.


You can display hexa values using NSLog method with %x formatter.

NSLog(@"Hex value: 0x%08x", 0x1234);

You can even display current method name in execution using NSLog method.
NSLog(@"%s", __PRETTY_FUNCTION__, nil);

Creating NSDate object from NSString using NSDateFormatter example

This example shows how to create an NSDate object from NSString using NSDateFormatter. The conversion work is done by NSDateFormatter object. See following code, it's simple enough to understand.


NSString *dateString = @"2010-04-16";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

// 포맷에 주의!
[dateFormatter setDateFormat:@"yyyy-MM-dd"];

NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:dateString];

NSDictionary and plist example

An example of creating NSDictionary object from plist file.
The plist provides the data to be filled in the NSDictionary object.
Following code fragment is collected from http://codersjunto.com/wp/?p=16
[NSDictionary and plist]

In your IPhone application add a New File/Other/Property List in my example MyTestList.plist. I then created three entries Name,Date,Debt and gave them some values.
In the code example below name, mydate, and debt are bound to labels on a view.


//Path get the path to MyTestList.plist
NSString *path=[[NSBundle mainBundle] pathForResource:@"MyTestList" ofType:@"plist"];
//Next create the dictionary from the contents of the file.
NSDictionary *dict=[NSDictionary dictionaryWithContentsOfFile:path];

//now we can use the items in the file.
self.name.text=[dict valueForKey:@"Name"] ;
NSLog(@"%@",[dict valueForKey:@"Name"]);
self.mydate.text=[dict valueForKey:@"Date"] ;
self.debt.text=[dict valueForKey:@"Debt"] ;
//change a value.
 [dict setValue:@"Jimmy" forKey:@"Name"];
//write changes back to file.
 [dict writeToFile:path atomically:YES];

Another example of NSMutableDictionary with NSEnumerator

Another example of NSMutableDictionary object manipulation with NSEnumerator interface. The object is created and initialized by three key-value pairs, then keyEnumerator method is called to create NSEnumerator object for the NSMutableDictionary object.


NSMutableDictionary *myDictionary = [[ NSMutableDictionary alloc]
init];
    [ myDictionary setObject:@"Keith" forKey:@"name"];
    [ myDictionary setObject:@"hacker" forKey:@"subject"];
    [ myDictionary setObject:@"4/9/2002" forKey:@"date"];

    NSEnumerator *enumerator = [ myDictionary keyEnumerator];
    NSString *key;
    while (key = [ enumerator nextObject]) {
        printf("%s\n", [[ myDictionary objectForKey:key] UTF8String]);
    }

NSMutableArray example

Here is a simple example to add elements in a NSMutableDictionary object  and go through a for loop to extract values by keys and make sure to release it whenever you finish using it. Note that NSDictionary is readonly. You should create NSMutableDictionary if you want to change the content of the dictionary.


NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
 [dict setObject:@"John" forKey:@"Firstname"];
 [dict setObject:@"Doe" forKey:@"Lastname"];
 [dict setObject:@"info at objectgraph.com" forKey:@"Email"];
 
 NSLog(@"%@", dict);
 
 NSArray *keys = [dict allKeys];
 
 // values in foreach loop
 for (NSString *key in keys) {
  NSLog(@"%@ is %@",key, [dict objectForKey:key]);
 }

NSDictionary iteration using NSEnumerator

An example for iterating NSDictionary object using NSEnumerator.
An NSDictionary object is created with some keys and values (all NSString objects).
NSEnumerator object is created from NSDictionary object by calling NSDictionary:keyEnumerator: method.

Following code is collected from http://www.cocoadev.com/index.pl?NSDictionary



int main(int argc, const char *argv[])
{
    NSDictionary *dict;
    NSEnumerator *enumerator;
    id key;
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    
    dict = [NSDictionary dictionaryWithObjectsAndKeys:
                   @"A beverage prepared by heating cocoa with water/milk",
                   @"cocoa", 
                   @"http://www.cocoadev.com/",
                   @"cocoadev", 
                   @"4 : a list (as of items of data or words) stored in a                         computer for reference (as for information retrieval                         or word processing)",
                   @"dictionary",
                   nil];
    
    // printf("entry for cocoa: %s\n\n",
    //        [[dict objectForKey:@"cocoa"]cString]);
    // Use of the cString method is discouraged ASCII is out Unicode is in.
    // Also watch out for [[dict objectForKey:@"cocoa"]cString] notice the
    // lack of a space between the receiver and the message.
    // And lastly since this is a Cocoa example why not use an NSLog()
    NSLog(@"entry for cocoa: %@", [dict objectForKey:@"cocoa"]);

    enumerator = [dict keyEnumerator];
    
    while ((key = [enumerator nextObject])) {
        //printf("%s : %s\n", [key cString],
        //        [[dict objectForKey: key] cString]);
        NSLog(@"%@ : %@", key, [dict objectForKey:key]);
    }
    
   [pool release];

    return 0;//NSApplicationMain(argc, argv);
}

NSDictionary example - creation.

One example of creating NSDictionary object with keys and values.
NSDictionary is a hash table with the (key, value) tuple inside.
Following code is collected from http://www.gnustep.it/nicola/Tutorials/BasicClasses/node25.html
------------------------------------------------

To create a NSDictionary, you can use the method
+dictionaryWithObjectsAndKeys:
which takes as argument a list of objects (to be considered in couples; the first one is the value, the second is the key); the list is terminated by nil. The following example creates the dictionary used as example in the previous section:
NSDictionary *dict;

dict = [NSDictionary dictionaryWithObjectsAndKeys:
               @"/opt/picture.png", @"Luca", 
               @"/home/nico/birthday.png", @"Birthday Photo", 
               @"/home/nico/birthday.png", @"Birthday Image", 
               @"/home/marghe/pic.jpg", @"My Sister", nil];
Please note the the keys follow their values rather than preceding them.

NSMutableArray sorting example - sortUsingSelector

A NSMutableArray sorting example using NSMutableArray:sortUsingSelector: method.
NSMutableArray:sortUsingSelector: method takes selector for a compare function as its argment. See following code.


NSMutableArray *a = [NSMutableArray arrayWithObjects:@"Cat", @"Dog", @"Fish", @"Squirrel", @"Bear", @"Turtle", nil];
[a sortUsingSelector:@selector(compare:)];

NSArray basic examples.

Some basic examples of NSArray class.
How to create an NSArray object.
How to initialized it.
How many elements in it.
How to add an object.
How to get an object at the specified index.




NSMutableArray *array;                                                           //simply defines a mutable Array

array = [[NSMutableArray alloc] init];                                     //saves memory for the Array and initializes it.

arrayCount = [array count];                                      //counts all objects of this array and puts it into the arrayCount variable

[array addObject:[NSNumber numberWithInt:15]];      // appends "15" to the (mutable) array

arrayVariable = [array objectAtIndex:378];            //returns the 379th Object of the array and puts it into arrayVariable 

NSArray iteration using NSEnumerator

Following code fragment shows how to iterator elements of an NSArray object using NSEnumerator object. The NSEnumerator object is simply used to display the content of the NSArray object.




NSEnumerator * enumerator = [myArray objectEnumerator];
id element;

while(element = [enumerator nextObject])
    {
    // Do your thing with the object.
    NSLog(element);
    }

Win32 CreateBitmap() example c c++

Following code fragment shows how to output an PNG image using Bitmap created by
CreateBitmap() function. Here, CPNGWrapper class is just a wrapper for libpng which does the chores on behalf of the user. After loading a PNG image, we create a bitmap by passing the image information(width, height, buffer) to CreateBitmap() Function. Then the Bitmap content is transferred to current window by BitBlt function.



                CPNGWrapper        *pPNG = new CPNGWrapper("./Manchuria.png");
                HDC                hDC = GetDC(hWnd);
                HDC                hMemDC = CreateCompatibleDC(hDC);
                HBITMAP            hOldBMP, hNewBMP;

                pPNG->read();
                pPNG->convert(PNG_PIXEL_BGRA_32);

                // Display Image onto Screen for validation.
                //
                hNewBMP = CreateBitmap(pPNG->getWidth(), pPNG->getHeight(), 1, 32, pPNG->getBuffer());
                hOldBMP = (HBITMAP)SelectObject(hMemDC, hNewBMP);

                BitBlt(hDC, 0, 0, pPNG->getWidth(), pPNG->getHeight(), hMemDC, 0, 0, SRCCOPY);

                SelectObject(hMemDC, hOldBMP);
                DeleteObject(hNewBMP);
                DeleteDC(hMemDC);
                ReleaseDC(hWnd, hDC);
                delete pPNG;

NSArray sortedArrayUsingSelector example objc

Following code is an example of NSArray:sortedArrayUsingSelector method.
The comparator is given as a selector argument. Here we used default case-insensitive compare function. NSArray:sortedArrayUsingSelector is frequently used in list arrangement and so on, so it's worth to remember this example.

NSArray *sortedArray =
    [myArray2 sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
    // This will return a sorted array that looks like [@"bar",@"baz",@"foo"]

NSArray creation example

Following code shows some basic NSArray creation examples.
You can see fiver other ways of creating NSArray objects.
NSArray is the most basic data structure (which is used for array and linked-list) in Apple's
objective C environment.


Code borrowed from http://www.icodeblog.com/2009/08/26/objective-c-tutorial-nsarray/


// I am using strings, but you can add just about any object to an NSArray
 
// Creates an NSArray with one object
NSArray  * myArray = [NSArray arrayWithObject:@"foo"];
 
// Creates an NSArray with multiple objects. Don't forget to add nil as the last object
NSArray  * myArray2 = [NSArray arrayWithObjects:@"foo",@"bar",@"baz",nil];
 
// Creates an NSArray from another NSArray
NSArray * myArray3 = [NSArray arrayWithArray:myArray2];
 
// This will create an NSArray from data on iCodeBlog.  Go ahead and try it out, this file exists on our servers and contains valid data.
NSArray * myArray4 = [NSArray arrayWithContentsOfURL:[NSURL URLWithString:@"http://my.own.url/foo.plist"]];
 
// Normal Initialization.
// 
NSArray * foo = [[NSArray alloc] initWithObjects:@"foo",@"bar",@"baz",nil]; 

Simple screen capture example - GDI version.

A Simple screen capture example using windows handle and BitBlt.
This mechanism works for both GDI and DirectX window mode.
However, this screen capture has its own weakness, low performance and
abnormal mouse behaviour. Use it just as reference.



// Functions for captureing WoW screen.
//
HWND        getWoWWindowHandle(void)
{
    HWND        wowWnd;


    //return GetDesktopWindow();

    // Try to find WoW window handle.
    //
    wowWnd = FindWindow(TEXT("GxWindowClass"), TEXT("월드 오브 워크래프트"));
    if( wowWnd )
    {
        // The window is found.
        //
        return wowWnd;
    }
    else
        return NULL;
}


void        captureWoWWindow(HDC hTgtDC)
{
    HWND        hSrcWnd;
    HDC            hSrcDC;

    // Get WoW Window Handle.
    //
    hSrcWnd = getWoWWindowHandle();
    if( hSrcWnd )
    {
        hSrcDC = GetDC(hSrcWnd);

        BitBlt(hTgtDC, 0, 0, 960, 640, hSrcDC, 0, 0, SRCCOPY | CAPTUREBLT);

        ReleaseDC(hSrcWnd, hSrcDC);
    }

    return;
}

Wednesday, May 4, 2011

pthread_detach example c c++

Name

pthread_detach - put a running thread in the detached state

Synopsis

#include <pthread.h>
int pthread_detach(pthread_t th);

Description

pthread_detach puts the thread th in the detached state. This guarantees that the resources consumed by thwill be freed immediately when th terminates. However, this prevents other threads from synchronizing on the termination of th using pthread_join. If, when pthread_detach is called, th has already terminated, all of th's remaining resources will be freed.
A thread can be created initially in the detached state, using the detachstate attribute to pthread_create(3) . In contrast, pthread_detach applies to threads created in the joinable state, and which need to be put in the detached state later.
After pthread_detach completes, subsequent attempts to perform pthread_join on th will fail. If another thread is already joining the thread th at the time pthread_detach is called, th will be detached and pthread_join will eventually return when th terminates but may not return with th's correct return code.

Return Value

On success, 0 is returned. On error, a non-zero error code is returned.

Errors

ESRCH
No thread could be found corresponding to that specified by th
EINVAL
the thread th is already in the detached state
 
#include <stdio.h> 
#include <string.h> 
#include <pthread.h> 
 
pthread_t threads[5]; 
int done[5]; 
 
void *thread_main(void *); 
 
int main(void) 
{ 
    int i; 
    int rc; 
    int status; 
     
    printf("pid=%d\n", getpid()); 
 
    for (i = 0; i < 5; i++) 
    {     
        done[i] = 0; 
        pthread_create(&threads[i], NULL, &thread_main, (void *)i); 
        printf("%d, %d\n", i, threads[i]); 
    } 
 
    for (i = 4; i >= 0; i--) 
    { 
        done[i] = 1; 
        rc = pthread_join(threads[i], (void **)&status); /* detach thead에서는 사용할 필요 없다. */ 
        if (rc == 0) 
        { 
            printf("Completed join with thread %d status= %d\n",i, status); 
        } 
        else 
        { 
            printf("ERROR; return code from pthread_join() is %d, thread %d\n", rc, i); 
                 return -1; 
        } 
    } 
 
    return 0; 
} 
 
void *thread_main(void *arg) 
{ 
    int i; 
    double result=0.0; 
 
    pthread_detach(pthread_self()); /* 쓰레드 분리 */ 
 
    printf("therad: %d, %d\n", (int)arg, getpid()); 
 
    while (!done[(int)arg]) 
    { 
            for (i=0; i < 1000000; i++) 
           { 
                 result = result + (double)random(); 
           } 
           printf("thread: %d, result = %e\n", (int)arg, result); 
    } 
 
    pthread_exit((void *) 0); 
} 
 

pthread_cancel example c c++

NAME         top

       pthread_cancel - send a cancellation request to a thread

SYNOPSIS         top

       #include <pthread.h>

       int pthread_cancel(pthread_t thread);

       Compile and link with -pthread.

DESCRIPTION         top

       The pthread_cancel() function sends a cancellation request to the thread
       thread.  Whether and when the target thread reacts to the cancellation
       request depends on two attributes that are under the control of that
       thread: its cancelability state and type.

       A thread's cancelability state, determined by pthread_setcancelstate(3),
       can be enabled (the default for new threads) or disabled.  If a thread has
       disabled cancellation, then a cancellation request remains queued until the
       thread enables cancellation.  If a thread has enabled cancellation, then
       its cancelability type determines when cancellation occurs. (pthread_cancel)


       A thread's cancellation type, determined by pthread_setcanceltype(3), may
       be either asynchronous or deferred (the default for new threads).
       Asynchronous cancelability means that the thread can be canceled at any
       time (usually immediately, but the system does not guarantee this).
       Deferred cancelability means that cancellation will be delayed until the
       thread next calls a function that is a cancellation point.  A list of
       functions that are or may be cancellation points is provided in
       pthreads(7).

       When a cancellation requested is acted on, the following steps occur for
       thread (in this order):

       1. Cancellation clean-up handlers are popped (in the reverse of the order
          in which they were pushed) and called.  (See pthread_cleanup_push(3).)

       2. Thread-specific data destructors are called, in an unspecified order.
          (See pthread_key_create(3).)

       3. The thread is terminated.  (See pthread_exit(3).)

       The above steps happen asynchronously with respect to the pthread_cancel()
       call; the return status of pthread_cancel() merely informs the caller
       whether the cancellation request was successfully queued.

       After a canceled thread has terminated, a join with that thread using
       pthread_join(3) obtains PTHREAD_CANCELED as the thread's exit status.
       (Joining with a thread is the only way to know that cancellation has
       completed.)

RETURN VALUE         top

       On success, pthread_cancel() returns 0; on error, it returns a nonzero
       error number.

ERRORS         top

       ESRCH  No thread with the ID thread could be found.

 
Example 

#include <stdio.h> 
#include <string.h> 
#include <pthread.h> 
 
pthread_t threads[5]; 
int done[5]; 
 
void *thread_main(void *); 
 
int main(void) 
{ 
    int i; 
    int rc; 
    int status; 
     
    printf("pid=%d\n", getpid()); 
 
    for (i = 0; i < 5; i++) 
    {     
        done[i] = 0; 
        pthread_create(&threads[i], NULL, &thread_main, (void *)i); 
        printf("%d, %d\n", i, threads[i]); 
    } 
 
    for (i = 4; i >= 0; i--) 
    { 
        rc = pthread_cancel(threads[i]); // 
        if (rc == 0) 
        { 
            // 자동종료 
            rc = pthread_join(threads[i], (void **)&status); 
            if (rc == 0) 
            { 
                printf("Completed join with thread %d status= %d\n",i, status); 
            } 
            else 
            { 
                printf("ERROR; return code from pthread_join() is %d, thread %d\n", rc, i); 
                     return -1; 
            } 
        } 
    } 
 
    return 0; 
} 
 
void *thread_main(void *arg) 
{ 
    int i; 
    double result=0.0; 
 
    printf("therad: %d, %d\n", (int)arg, getpid()); 
 
    while (!done[(int)arg]) 
    { 
      for (i=0; i < 1000000; i++) 
        { 
          result = result + (double)random(); 
      } 
        printf("thread: %d, result = %e\n", (int)arg, result); 
    } 
 
    pthread_exit((void *) 0); 
} 

pthread example - basic 2

A simple pthread example which creates a thread with pthread_create() and
exits with pthread_exit() and pthread_join().

Code for the ptrehad example is listed below.


#include <stdio.h> 
#include <string.h> 
#include <pthread.h> 
 
pthread_t threads[5]; 
int done[5]; 
 
void *thread_main(void *); 
 
int main(void) 
{ 
    int i; 
    int rc; 
    int status; 
     
    printf("pid=%d\n", getpid()); 
     
    for (i = 0; i < 5; i++) 
    {     
        done[i] = 0; 
        pthread_create(&threads[i], NULL, &thread_main, (void *)i); 
        printf("%d, %d\n", i, threads[i]); 
    } 
 
    for (i = 4; i >= 0; i--) 
    { 
        done[i] = 1; 
             rc = pthread_join(threads[i], (void **)&status); 
        if (rc == 0) 
        { 
            printf("Completed join with thread %d status= %d\n",i, status); 
        } 
        else 
        { 
            printf("ERROR; return code from pthread_join() is %d, thread %d\n", rc, i); 
                          return -1; 
        } 
    } 
 
    return 0; 
} 
 
void *thread_main(void *arg) 
{ 
    int i; 
    double result=0.0; 
 
    printf("therad: %d, %d\n", (int)arg, getpid()); 
 
    while (!done[(int)arg]) 
    { 
       for (i=0; i < 1000000; i++) 
          { 
               result = result + (double)random(); 
          } 
          printf("thread: %d, result = %e\n", (int)arg, result); 
    } 
 
    pthread_exit((void *) 0); 
} 
 

glTexImage2D example C/C++

An example of glTextImage2D() function in C/C++ language. Collected from http://stackoverflow.com/questions/679210/how-can-i-use-a-dynamically-sized-texture-array-with-glteximage2d
glTexImage2D() is used to load an image to GPU memory.

Currently, I'm able to load in a static sized texture which I have created. In this case it's 512 x 512.
This code is from the header:
#define TEXTURE_WIDTH 512
#define TEXTURE_HEIGHT 512
GLubyte textureArray[TEXTURE_HEIGHT][TEXTURE_WIDTH][4];
Here's the usage of glTexImage2D:
glTexImage2D(
        GL_TEXTURE_2D, 0, GL_RGBA,
        TEXTURE_WIDTH, TEXTURE_HEIGHT,
        0, GL_RGBA, GL_UNSIGNED_BYTE, textureArray);
And here's how I'm populating the array (rough example, not exact copy from my code):
for (int i = 0; i < getTexturePixelCount(); i++)
{
    textureArray[column][row][0] = (GLubyte)pixelValue1;
    textureArray[column][row][1] = (GLubyte)pixelValue2;
    textureArray[column][row][2] = (GLubyte)pixelValue3;
    textureArray[column][row][3] = (GLubyte)pixelValue4;
}
How do I change that so that there's no need for TEXTURE_WIDTH and TEXTURE_HEIGHT? Perhaps I could use a pointer style array and dynamically allocate the memory...

OpenGL SwapBuffers() example Windows.

SwapBuffers(hdc) function is used to switch front and back buffer of OpenGL surface.
So, it effectively requires double-buffering. In OpenGL, your drawing is not updated to screen until you call SwapBuffers(hdc) function.

void    DrawIt()
{
    // Drawing OpenGL Geometry.
    //
    glClear(GL_COLOR_BUFFER_BIT);

    //glPushMatrix();

    glScalef(0.5f, 0.5f, 0.5f);
    glBegin(GL_TRIANGLES);
        glColor3f(1.0f, 0.0f, 0.0f);
        glVertex3f(-1.0f, -1.0f, -1.0f);
        glColor3f(0.0f, 1.0f, 0.0f);
        glVertex3f(1.0f, -1.0f, -1.0f);
        glColor3f(0.0f, 0.0f, 1.0f);
        glVertex3f(0.0f, 1.0f, -1.0f);
    glEnd();

    //glPopMatrix();

    SwapBuffers(g_hDC);

    return;
}

OpenGL Initialization example.

Following code is OpenGL initialization example using WGL.
First, it creates a GL surface for rendering and associate it with
current windows Device Context. WGL(an Windows version of EGL) is
used to perform this work. [tag: OpenGL Initialization]

BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
   HWND hWnd;

    // Adjust the window size.
    RECT    kRect = { 0, 0, g_iWidth-1, g_iHeight-1 };

    AdjustWindowRect(&kRect, WS_OVERLAPPEDWINDOW, true);

    hInst = hInstance;

    hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
      0, 0, kRect.right - kRect.left + 1, kRect.bottom - kRect.top + 1, NULL, NULL, hInstance, NULL);

   if (!hWnd)
   {
      return FALSE;
   }

   // Get DC for OpenGL.
   g_hDC = GetDC(hWnd);

   {
        // Select format for drawing surface.
        PIXELFORMATDESCRIPTOR    kPFD;
        int                        iPixelFormat;
        BOOL                    bSuccess;

        memset(&kPFD, 0, sizeof(PIXELFORMATDESCRIPTOR));
        kPFD.nSize = sizeof(PIXELFORMATDESCRIPTOR);
        kPFD.nVersion = 1;
        kPFD.dwFlags = PFD_DRAW_TO_WINDOW |
                        PFD_SUPPORT_OPENGL |
                        PFD_GENERIC_ACCELERATED |
                        PFD_DOUBLEBUFFER;
        kPFD.iPixelType = PFD_TYPE_RGBA;
        kPFD.cColorBits = 24;
        kPFD.cDepthBits = 16;
        kPFD.cStencilBits = 8;

        // Choose pixel format.
        iPixelFormat = ChoosePixelFormat(g_hDC, &kPFD);
        if( iPixelFormat == 0 )
        {
            ReleaseDC(hWnd, g_hDC);
            return -1;
        }

        // Set pixel format.
        bSuccess = SetPixelFormat(g_hDC, iPixelFormat, &kPFD);
        if( !bSuccess )
        {
            ReleaseDC(hWnd, g_hDC);
            return -1;
        }

        // Create openGL context.
        g_hGLRC = wglCreateContext(g_hDC);
        if( !g_hGLRC )
        {
            ReleaseDC(hWnd, g_hDC);
            return -3;
        }

        // Make current context.
        bSuccess = wglMakeCurrent(g_hDC, g_hGLRC);
        if( !bSuccess )
        {
            wglDeleteContext(g_hGLRC);
            ReleaseDC(hWnd, g_hDC);
            return -4;
        }

        // Initialize OpenGL Environment.
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();

        // Set viewport.
        glViewport(0, 0, g_iWidth, g_iHeight);

        // Set ModelView matrix.
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();

        // Set clear color.
        glClearColor(0.2f, 0.0f, 0.0f, 1.0f);
   }

   ShowWindow(hWnd, nCmdShow);
   UpdateWindow(hWnd);

   return TRUE;
}