C基礎 如何讓代碼只執行一次


1.0 最簡單, 最高效的方式


    C 代碼運行起點 main 就是個大單例函數. 如果把函數注冊在其里面, 那么一定很可以 :)
// 某個庫需要初始化的函數
void log_init(void) {
    ... ... 
}

int main(int argc, char * argv[]) {
    ... ...
    extern void log_init(void);
    log_init()
    ... ...    
    return 0;
}

是不是, 很輕松的完成了初始化工作.
不妨贈送一個好用的宏, 用於處理這類事情
//
// EXTERN_RUN - 簡單的聲明, 並立即使用的宏
// ftest    : 需要執行的函數名稱
// ...      : 可變參數, 保留
//
#define EXTERN_RUN(ftest, ...)  \
do {                            \
    extern void ftest();        \
    ftest (__VA_ARGS__);        \
} while(0)
用起來更簡單, 可以插在代碼的任何一處
EXTERN_RUN(log_run);

2.0 多線程模式, 如何搞起呢


    繼續看下面例子 once.c 
#include <stdio.h>
#include <pthread.h>

static void _once(void) {
    static long _cnt;

    printf("_once _cnt = %ld\n", ++_cnt);
}

//
// pthread_once 感受
//
int main(int argc, char * argv[]) {
    pthread_once_t once = PTHREAD_ONCE_INIT;

    puts("pthread_once 感受開始 ... ");
    pthread_once(&once, _once);
    pthread_once(&once, _once);
    puts("pthread_once 感受結束 ... ");

    return 0;
}

gcc -g -Wall -o once.out once.c -lpthread
最終運行結果, 也是如我們所料那樣

pthread_once 實際開發中多用於初始化線程私有變量. 其內部實現加鎖的.
不妨問個小問題, 如果需要你去實現 pthread_once 你會怎么分析呢 ? 

這個問題好解答也不好解答. 
核心亮點在於 pthread_once 運行的函數實體崩潰了. 多線程之間如何避免死鎖. 
不妨參照下面 winds 上面 pthread_once 一位大佬的實現:
#include "pthread.h"
#include "implement.h"

/* [i_a] simple wrapper ensures correct calling convention for all */
static void PTW32_CDECL
ptw32_mcs_lock_cleanup(void *args)
{
	ptw32_mcs_local_node_t *node = (ptw32_mcs_local_node_t *)args;
	ptw32_mcs_lock_release(node);
}

int
pthread_once (pthread_once_t * once_control, void (PTW32_CDECL *init_routine) (void))
{
  if (once_control == NULL || init_routine == NULL)
    {
      return EINVAL;
    }

  if ((PTW32_INTERLOCKED_LONG)PTW32_FALSE ==
      (PTW32_INTERLOCKED_LONG)PTW32_INTERLOCKED_EXCHANGE_ADD_LONG((PTW32_INTERLOCKED_LONGPTR)&once_control->done,
                                                                  (PTW32_INTERLOCKED_LONG)0)) /* MBR fence */
    {
      ptw32_mcs_local_node_t node;

      ptw32_mcs_lock_acquire((ptw32_mcs_lock_t *)&once_control->lock, &node);

      if (!once_control->done)
	{

#if defined(PTW32_CONFIG_MSVC7)
#pragma inline_depth(0)
#endif

	  pthread_cleanup_push(ptw32_mcs_lock_cleanup, &node);
	  (*init_routine)();
	  pthread_cleanup_pop(0);

#if defined(PTW32_CONFIG_MSVC7)
#pragma inline_depth()
#endif

	  once_control->done = PTW32_TRUE;
	}

      ptw32_mcs_lock_release(&node);
    }

  return 0;

}				/* pthread_once */
核心是通過 pthread_cleanup_push 和  pthread_cleanup_pop 解決崩潰死鎖問題.
當然還有一種思路, 可以解決上面問題. 不妨往下看.

3.0 跳過鎖問題, 嘗試原子操作


    先舉個小例子 
#include <stdio.h>

static void _once(void) {
    static long _cnt;

    printf("_once _cnt = %ld\n", ++_cnt);
}

//
// run once 感受
//
int main(int argc, char * argv[]) {
    puts("run once 感受開始 ... ");

    {
        static int _done;
        if (__sync_bool_compare_and_swap(&_done, 0, 1)) {
            _once();
        }

        if (__sync_bool_compare_and_swap(&_done, 0, 1)) {
            _once();
        }
    }

    puts("run once 感受結束 ... ");
    return 0;
}
運行展示:

這里通過 GCC 提供的 原子交換 __sync_bool_compare_and_swap 解決的. 

不妨繼續贈送的封裝宏, 來完成上面操作
#define ONCE_RUN(code) {                                    \
    static int _done;                                       \
    if (!_done) {                                           \
        if (__sync_bool_compare_and_swap(&_done, 0, 1)) {   \
            code                                            \
        }                                                   \
    }                                                       \
}
因為是原子操作, 沒有鎖那么重, 自然出了問題也不會引起死鎖問題.  

當然有人說 pthread, __sync_xxx 都是和 GCC 綁定的, 那么 CL 能不能使用了. 當然也是可以的.

pthread 跨平台 - https://github.com/wangzhione/structc/blob/master/structc/system/thread.h

atomic 跨平台 - https://github.com/wangzhione/atomic/blob/master/atomic/atom.h

通過上面基礎封裝庫支持, 用 C 寫系統應用相關代碼還是很好搞的.

把酒滿上, 還能再寫幾行代碼

    有問題, 是肯定的. 歡迎指正, 更新是共同提高的過程.

老鼠愛大米 - http://music.163.com/m/song?id=308789&userid=16529894

回頭看看, 時間好快呀.  那些個一塊補習, 為了玩的伙伴們, 二胎孩子都快上學了. 
哈哈. 
咱們一線禿頭兵還在為了 窮 而沖鋒陷陣 (°ー°〃)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM