sourcecode

Thursday, July 5, 2012

pthread_create()

http://www.yolinux.com/TUTORIALS/LinuxTutorialPosixThreads.html
http://www.cs.cf.ac.uk/Dave/C

Tried to find the simplest example of using pthread_create for a beginner. The man page of pthread_create, again, is rather a reference for experts who already know how to use pthread_create.

Here I have the simplest working code without all the distractions:
#include <stdio.h>
#include <pthread.h>

void* threadFunction(){//the function is the entry point of a new thread
  printf("Catch = %d\n",22);
}

int main(){

  pthread_t threadId;//to record the thread id of the newly created thread
  //effectively pthread_t is type unsigned long int

  pthread_create(&threadId, NULL, threadFunction, NULL);
  //threadFunction, inputArg together is a function call equivalent to the
  //more familiar form: threadFunction(inputArg);

  pthread_join(threadId,NULL);
  //this function call forces the main() is waiting for the thread to complete. 
  //(for the thread to "join" back?)
  //Otherwise, the main
  //may exit before the thread finishes, thus aborts the thread prematurely

  printf("threadId = %lu\n",threadId);

  return 0;
  }
 

The thread function takes exactly one entrance parameter,  similar to main() you can have main(char argc, char** argv). It is common practice to have the entrance parameter be a struct so that complicated data can be passed into the thread.

#include <stdio.h>
#include <pthread.h>

void* threadFunction(void* threadFunctionArg){
  int* pMax = threadFunctionArg;
  printf("Double the input =%d\n",*pMax * 2);
}


int main(){
  int num=5;//some information to pass to the new thread

  pthread_t threadId;//to record the thread id of the newly created thread
  //effectively pthread_t is type unsigned long int

  int threadStatus;//to record the return status of the new thread
  //0 means good, otherwise an error number is recorded.

  void* inputArg = &num;//used to pass into the thread function

  threadStatus = pthread_create(&threadId, NULL, threadFunction, inputArg);
  //threadFunction, inputArg together is a function call equivalent to the
  //more familiar form: threadFunction(inputArg);

  pthread_join(threadId,NULL);
  //the main() is waiting for the thread to complete. Otherwise, the main
  //may exit before the thread finishes, thus aborts the thread prematurely

  printf("threadId = %lu\n",threadId);

  printf("threadStatus = %d\n",threadStatus);

  return 0;
  }
/********************END******************/

No comments: