How do I create a new thread?

Discussion in 'Public Game Developers Forum' started by kohjingyu, Aug 20, 2009.

  1. kohjingyu

    kohjingyu Well-Known Member

    Mar 20, 2009
    1,770
    0
    0
    Student/Developer
    Singapore
    Hey guys,
    I'm not sure about how to create a new thread in the game. I think it's something like:

    Code:
    [detach newThread ....]
    
    Can anyone help?

    Also can the function called by the thread be also called by a timer?

    Thanks.
     
  2. PixelthisMike

    PixelthisMike Well-Known Member

    You need
    Code:
    detachNewThreadSelector:toTarget:withObject:
    It is a static method of the NSThread class. It doesn't say there what the parameter to the selector actually is, just that there must be one and only one.

    If the method you want to share between the timer and the thread firing doesn't actually use the parameter for anything just cast it as id and it shouldn't matter.

    I hope you know what you're getting yourself in for working with threads! Concurrency is a nasty but powerful beast!
     
  3. kohjingyu

    kohjingyu Well-Known Member

    Mar 20, 2009
    1,770
    0
    0
    Student/Developer
    Singapore
    Haha, so I can do:

    Code:
    
    - (void)viewDidLoad
    {
          detachNewThreadSelector:aLoop toTarget:object
    
          [super viewDidLoad];
    }
    
    - (void)aLoop
    {
         //Do something
    }
    
    
    Can I specify a certain amount of interval for a thread? And what are the disadvantages to using a thread instead of a timer? I know that it would run faster, about 10 fps faster...
     
  4. PixelthisMike

    PixelthisMike Well-Known Member

    Almost, you do:

    Code:
    [NSThread detachNewThreadSelector:@selector(aLoop:) toTarget:self withObject:nil];
    And your aLoop method must take a parameter, it looks like it is the object specified at by the withObject parameter. You really should check the NSThread reference as there is info there relating to autorelease pools and suchforth.

    Having told you all that it seems to me that a thread is not what you are looking for if you are comparing a thread and a timer as they are very different beasts! Your program switches execution between all the threads it has running as it pleases. It could be in the middle of doing something in one function and then jump off to another thread. This is the essence of concurrency. There is no way to control when your program jumps between threads so no you can't set a time interval on it.

    What are you trying to achieve exactly?
     
  5. kohjingyu

    kohjingyu Well-Known Member

    Mar 20, 2009
    1,770
    0
    0
    Student/Developer
    Singapore
    I'm trying to make my game loop threaded instead of using a timer, as it would mean it would run faster. Should I use a thread? Or a timer?

    Thanks.
     

Share This Page