Data between NSThread

214 views Asked by At

I'll explain my problem. I need to maintain a tcp connection while my app is running, so I need to have regard to the connection on a background thread. I use the following to connect the socket and works well.

on connection.m

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

-(void)Connect {

        CFReadStreamRef readStream;
        CFWriteStreamRef writeStream;
        CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)IP,PORT, &readStream, &writeStream);

        inputStream = (__bridge NSInputStream *)readStream;
        outputStream =(__bridge NSOutputStream *)writeStream;

       [inputStream setDelegate:self];
       [outputStream setDelegate:self];

       [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
       [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
       [inputStream open];
       [outputStream open];
       [[NSRunLoop currentRunLoop] run];

}

-(void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {
  //all the code to receive data 
}

Now, the connection is working on a different thread to main thread. and I know that if I send something to the main thread I can use this,

   performSelectorOnMainThread

or

   dispatch_async(dispatch_get_main_queue(), ^{ ... do stuff

but if what I want is to send something through the outputstream by pressing a button in my view, the function is called,but outputstream is null. I think is because isn't in the thread where the connection is running.

how I can make that function is executed in the thread where I have the connection?

any help is well appreciated

2

There are 2 answers

1
RishiG On

Can you just use performSelector:OnThread:?

4
Mahmoud Fayez On

Make NSMutableArray with NSLock to protect it.

Main thread (UI) add items to the end of the list.

TCP thread pool the array to make sure it has something and consumes it.

Each of those two threads must lock the NSLock instance before trying to access the array then unlock it once they are done.

Here is a code snippet that may help you:

NSLock* pDataProtector;
NSMutableArray pMessageToBeProcessed;
// init the data variables when the program starts
pDataProtector = [NSLock new];
pMessageToBeProcessed = [[NSMutableArray alloc] init];

// UI code
[pDataProtector lock];
// add item to the array
[pDataProtector unlock];

// in another thread;
while(1)
{
    [pDataProtector lock];
    // if there is an item in the array get it in local var and delete it.
    [pDataProtector unlock];
    //if the local var has a value process it otherwise wait 10 seconds check NSThreads to wait 10 seconds.
}