Linux線程(1): 線程的建立

來源:互聯網
上載者:User

1. 概念:

    線程與進程是不同的, 準確地說, 進程可以由多個線程組成, 線程是進程的組成元素. 預設情況下, 一個進程只是由一個線程構成, 它串列執行該進程要執行的任務. 多線程情況下, 每個線程執行各自的任務, 它們之間更多是並行的. 線程的作用具體有:

  • 在單進程環境中執行多個任務.
  • 共用該進程的組成組件, 如檔案描述符和記憶體, 但需要較為複雜的機制.
  • 同步和非同步執行.
  • 線程改善輸送量, 由串列轉化為並行, 交叉執行.
  • 線程的特徵測試宏_POSIX_THREADS:
    • 用#ifdef測試上述宏以確定是否支援線程.
    • 用_SC_THREADS常數調用sysconf函數, 以確定是否支援線程

 

2. 線程標識(ID):

  • 線程有ID, 但不是系統唯一, 而是進程環境中唯一有效.
  • 線程的控制代碼是pthread_t類型, 該類型不能作為整數處理, 而是一個結構.

下面介紹兩個函數:

  • 標頭檔: <pthread.h>
  • 原型: int pthread_equal(pthread_t tid1, pthread_t tid2);
  • 傳回值: 相等返回非0, 不相等返回0.
  • 說明: 比較兩個線程ID是否相等.

 

  • 標頭檔: <pthread.h>
  • 原型: pthread_t pthread_self();
  • 傳回值: 返回調用線程的線程ID.

 

3. 線程建立:

    在執行中建立一個線程, 可以為該線程分配它需要做的工作(線程執行函數), 該線程共用進程的資源. 建立線程的函數pthread_create()

  • 標頭檔: <pthread.h>
  • 原型: int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(start_rtn)(void), void *restrict arg);
  • 傳回值: 成功則返回0, 否則返回錯誤編號.
  • 參數:
    • tidp: 指向新建立線程ID的變數, 作為函數的輸出.
    • attr: 用於定製各種不同的線程屬性, NULL為預設屬性.
    • start_rtn: 函數指標, 為線程開始執行的函數名.
    • arg: 函數的唯一無類型(void)指標參數, 如要傳多個參數, 可以用結構封裝.

 

4. 執行個體:

main.c代碼:

#include <pthread.h>

pthread_t ntid; /**//* save thread ID */

/**//* print process ID and thread ID */
void printids(const char *s)
...{
    pid_t pid;
    pthread_t tid;

    pid = getpid();
    tid = pthread_self();
    printf(%s pid %d tid %d (0x%x) ", s, pid, tid, tid);
}

/**//* thread process func */
void *thread_proc(void *arg)
...{
    printids("new thread: ");
    return NULL;
}

/**//* main func */
int main()
...{
    int err;
    
    /**//* create  a thread */
    err = pthread_create(&ntid, NULL, thread_proc, NULL);
    
    /**//* error handler */
    if (err != 0)
        perror("can't create thread");

    printids("main thread: ");
    sleep(1);
    
    return 0;
}

 

編譯命令:

gcc -o test main.c -lpthread

    在這個例子中, 可能會有人疑問為什麼在main中加上sleep, 這是因為主線程需要休眠, 否則可能會比新線程更早退出, 這個在新線程運行前整個進程可能已經終止了. 所以加上sleep讓主線程休眠一下, 確保新線程先完成.

    在你的Linux中跑一下這個代碼, 看看線程ID有什麼特點.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.