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.

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值