简体   繁体   中英

how to write pthread_create on the same function?

Could someone please help with this? I have the following:

// part_1
if (pthread_create(&threadID, NULL, ThreadMain, 
    (void *) clientSocket) != 0) {
    cerr << "Unable to create thread" << endl;
    exit(1);
}

// part_2
void *ThreadMain(void *clientSocket) {

  pthread_detach(pthread_self()); 

  ...

  delete (TCPSocket *) clientSocket;
  return NULL;
}

I would to have part_2 in part_1 ( I mean without calling TreadMain() function )

thanks for your replies

What if you could do this?

pthread_create() has to create a new stack for the new thread to use. If pthread_create() copied the existing thread's old stack into a separate block of memory to create a new stack, then what would happen to local variables that point to other local variables? The local variables on the new stack would point to the old stack. When the thread using the old stack (the one that called pthread_create() ) returns or overwrites them, those variables start pointing to invalid data.

But what about fork() ? Why doesn't fork() take a function pointer like pthread_create() ? Well, unlike pthread_create() , the new thread of execution created by fork() doesn't have to live in the same address space as the old thread of execution, because they are in separate processes. fork() clones the parent process's virtual address space, stack, heap, and all. The child process's stack variables have the same virtual addresses as the corresponding variables in the parent process. So all of the pointers in the new child process continue to be valid*, no matter what the old parent process does with the memory.

* Nitpicker's corner: excluding pointers that were invalid to begin with, as well as memory that is deliberately shared

If all you want to do is simply move the function for part2 inside part1, you can create a local class inside of part1, with a static member function...

class LocalFunctor
{
public:
   static void *ThreadFunc(void* clientSocket)
   {
      pthread_detach(pthread_self());
      ...
      delete (TCPSocket *) clientSocket;       
      return NULL;  
    }
};

then call LocalFunctor::ThreadFunc within pthread_create

pthread_create(&threadID, NULL, LocalFunctor::ThreadFunc,(void *) clientSocket)

If you're going to do this more than once, look at boost::thread or wrap this up inside a template helper class.

You could get an Apple Macintosh computer with OS 10.6 and start programming with Grand Central Dispatch. Apple added some new C compiler features that do almost exactly what you seem to want. They're called Blocks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM