Multithreading in C and Java

Summary about mutlti-threading in C and Java
  1. If the main thread terminates, then the whole program dies, too. So if you
  want to run some tasks in a sub thread, you must guarantee that sub thread

  terminates before main thread.


  2. If you want to execute some task in a separate thread and wait until its
  termination, you should use pthread_join rather than condition and mutex.
  pthread_join is like waitpid, it suspend the calling thread until another
  thread terminates and you can retrieve thread's termination status through

  pthread_join which is much more difficult to do using condition and mutex.


  3. PTHREAD_MUTEX_INITIALIZER and PTHREAD_COND_INITIALIZER are implemented as
  macros. So when you use them incorrectly, you will get very confucious
  compiling error messages. For example,
      ...
    static pthread_mutex_t lock;
    ...
    43       lock = PTHREAD_MUTEX_INITIALIZER;
    ...
  If you compile, you will get:
      43: error: expected expression before token '{'
  The most weird thing is that there is no such token '{'. We can imagine that
  PTHREAD_MUTEX_INITIALIZER is implemented as macro.
  In addition we have two ways to initialize mutex and conditions,
    1. initialize them when declaring them.
       
        static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
        static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

    2. use initializing functions after declaration.
        
        pthread_mutex_init( &lock, NULL );
        pthread_cond_init( &cond, NULL );

  4. When you wait a condition, you must lock its mutex, when you signal a
  condition, you MUST NOT lock the mutex. MAKE sure you change the condition

  before signaling.


  5. Thread has its local stack frame, just like a function. Any local
  variable(auto variables, declared in the thread) becomes invalid when thread
  exits. So you should NEVER return a auto variable or put an auto variable
  into global data strutures.

你可能感兴趣的:(JOIN,thread,c,token,multithreading,variables)